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.
这道题目是hard 题目。
既然是找BST 树的Max Sum, 那么就一边判断子树是不是BST,一边更新maxSum。
判断子树是不是BST的办法也是用divide conque。一个BST树中序遍历完肯定也是个递增的。
判断左右子树是不是BST。如果其中一个子树不是BST,那这颗子树肯定也不是BST。
如果左右子树都是BST,再判断下root的数值是不是大于左子树的最大node,并且小于右子树的最小node。
这样就能返回到上一层了。
这么看来,必须返回三个元素,min,max以及isBST。
但是对于这个问题来讲,还得多返回一个元素,这颗子树的sum。当这个子树是BST树的时候,动态的更新maxVal。
以下是代码了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxSum=INT_MIN;
struct retVal {
int min;
int max;
int sum;
bool isBST;
};
//pair<int min, int max>
struct retVal isBST(TreeNode* root) {
struct retVal ret;
if(root == nullptr) {
ret.min = INT_MAX;
ret.max = INT_MIN;
ret.sum = 0;
ret.isBST = true;
if (ret.sum > maxSum)
maxSum = ret.sum;
return ret;
}
struct retVal l, r;
l = isBST(root->left);
r = isBST(root->right);
if(l.isBST && r.isBST && root->val > l.max && root->val < r.min) {
ret.min = min(l.min, root->val);
ret.max = max(r.max, root->val);
ret.sum = l.sum+r.sum+root->val;
ret.isBST = true;
if(ret.sum > maxSum)
maxSum = ret.sum;
return ret;
}
else {
ret.isBST = false;
}
return ret;
}
int maxSumBST(TreeNode* root) {
if(root == nullptr)
return 0;
isBST(root);
if(maxSum < 0)
maxSum =0;
return maxSum;
}
};