原题链接在这里: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 }标签:node,Binary,TreeNode,val,BST,Sum,int,null,root From: https://www.cnblogs.com/Dylan-Java-NYC/p/18174082