首页 > 其他分享 >LeetCode 1373. Maximum Sum BST in Binary Tree

LeetCode 1373. Maximum Sum BST in Binary Tree

时间:2024-05-05 23:34:34浏览次数:24  
标签:node Binary TreeNode val BST Sum int null root

原题链接在这里:https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/description/

题目:

Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
Output: 20
Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.

Example 2:

Input: root = [4,3,null,1,2]
Output: 2
Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.

Example 3:

Input: root = [-4,-2,-5]
Output: 0
Explanation: All values are negatives. Return an empty BST.

Constraints:

  • The number of nodes in the tree is in the range [1, 4 * 104].
  • -4 * 104 <= Node.val <= 4 * 104

题解:

Bottom up DFS. 

DFS state needs the current root node.

DFS returns an array with subtree min value, max value and sum. If the subtree is not a BST, then return null.

Check both left and right subtrees returned array are not null and rootval val is within (left substree.max, right subtree. min).

If current node could also be a subtree. update the res.

Note: when return current node subtree min and max, it needs to do Math.min(l[0], root.val) and Math.max(r[1], root.val). Since previous l[0] and r[1] could be Integer.MIN_VALUE or Integer.MAX_VALUE.

Time Complexity: O(n). n is number of nodes in the tree.

Space: O(h). The height of the tree.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     int res = 0;
18     public int maxSumBST(TreeNode root) {
19         dfs(root);
20         return res;
21     }
22 
23     private int[] dfs(TreeNode root){
24         if(root == null){
25             return new int[]{Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
26         }
27 
28         int[] l = dfs(root.left);
29         int[] r = dfs(root.right);
30         if(l == null || r == null || root.val <= l[1] || root.val >= r[0]){
31             return null;
32         }
33         
34         int total = l[2] + r[2] + root.val;
35         res = Math.max(res, total);
36         int min = Math.min(l[0], root.val);
37         int max = Math.max(r[1], root.val);
38         return new int[]{min, max, total};
39     }
40 }

类似Largest BST Subtree.

标签:node,Binary,TreeNode,val,BST,Sum,int,null,root
From: https://www.cnblogs.com/Dylan-Java-NYC/p/18174082

相关文章

  • ABC240Ex Sequence of Substrings
    ABC240ExSequenceofSubstringsLIS的好题改编。约定\(S(l,r)\)为字符串\(s\)中第\(l\)位到底\(r\)​位。\(S(l,r)<S(x,y)\)为字符串中\([l,r]\)的子串字典序比\([x,y]\)的子串小。前置LIS的\(n\logn\)求法。题解我们考虑按照类似于朴素LIS的方式设状......
  • BinaryTree_CountLeafNode
    /*******************************************************************************************************@filename: :StacksSimulateQueue*@brief :两个栈实现队列的功能*@author :[email protected]*@date :2024/05/04*@version......
  • 关于在Interface和Abstract Class间选择的一些思考
    本文系笔者在学习软件构造课程期间所写,不保证通用性和正确性,仅供参考。基于课程要求,本文所涉及语言为Java。目录前言接口:组件思想"CompositionoverInheritance"何时选择继承类结语一、前言与简要介绍在学习软件构造课程之前,自己写代码遇到需要复用类中功能时,基本......
  • 题解【[ABC147F] Sum Difference】
    题目链接下为口胡题解:入手方向推导:直接考虑题目所给式子显然困难:\[w(S)=\sum_{i\inS}A_i-\sum_{i\notinS}A_i\]因为两个式子虽然相关但是都在变化,不妨转化为:\[w(S)=2\times\sum_{i\inS}A_i-\sum_{i=1}^nA_i\]这样只用求出有多少个不同的\(\sum_{i\inS}A_i\)。由于......
  • excel - SUMIF的使用
    SUMIF(range,criteria,[sum_range])range是你要根据条件进行检查的单元格区域。criteria是根据其检查range的条件。这个条件可以是数字、表达式、或文本字符串。[sum_range]是可选的参数,当要求和的数字位于与range不同的区域时使用。如果省略sum_range,Excel会默认......
  • 题解:AT_abc298_h [ABC298Ex] Sum of Min of Length
    分析模拟赛签到题。考虑分讨。分两种情况:\(L=R\)。\(L\neR\)。对于第\(1\)种情况,用换根DP求一个\(i\)为根时所有点的深度和就行。对于第\(2\)种情况,钦定$dep_R\gedep_L$。很显然,\(R\)为根的子树中所有点都是离\(R\)更近。假设在\(L\)到\(R\)的路径......
  • CompareBinaryTreeDepth
    /*******************************************************************************************************@filename: :CompareBinaryTreeDepth*@brief :采用递归的方式来计算二叉树的深度*@author :[email protected]*@date :2024/05/03*......
  • 题解:CF607E Cross Sum
    Problem给定\(N\)条不平行的直线\(y=\frac{k_i}{1000}x+\frac{b_i}{1000}\),\(N\)条直线总共会有\(\frac{N(N-1)}{2}\)个交点(包含在同一个位置的点,即相同位置算不同的点),找出距离原点前\(K\)近的交点的距离和。$2\leN\le5\times10^4$,\(1\leK\le\frac{N(N-1)}{2}\)......
  • Educational Codeforces Round 165 (Rated for Div. 2) C. Minimizing the Sum题解
    题意CodeforcesRound809(Div.2)D1.ChoppingCarrots(EasyVersion)给你两个整数\(n(1\len\le3e5),k(0\lek\le10)\),一个数组\(a(1\lea_i\le10^9)\)。你可以进行如下操作最多\(k\)次:选定一个数\(i(1\lei\len)\),让其变为相邻的数(变为\(a_{i-1},a_{i......
  • [atcoder 351] [F Double Sum] [线段树]
    解法,使用线段树。请看代码:importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.math.BigInteger;importjava.util.StringTokenizer;publicclassMain{staticclassSegmentNode{intleft;......