Given a binary tree, determine if it is a valid 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.
在这道题目中,需要知道左右子树的最大值和最小值,才能使用递归,所以在函数中要涉及到两个输出,所以函数的参数列表中,需要使用两个引用 &maxRoot,&minRoot。而且务必注意的是,函数中需要对这两个数赋值啊………
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
int max=INT_MIN,min=INT_MAX;
return sub(root,max,min);
}
bool sub(TreeNode *root,int &maxRoot,int &minRoot ){
if(root==NULL) return true;
int maxLeft=INT_MIN,maxRight=INT_MIN,minLeft=INT_MAX,minRight=INT_MAX;
if(!(sub(root->left,maxLeft,minLeft)&&sub(root->right,maxRight,minRight))) return false;
if(root->val<=maxLeft||(root->val>=minRight)) return false;
int tempmax=max(maxLeft,maxRight);
int tempmin=min(minLeft,minRight);
maxRoot=max(tempmax,root->val);
minRoot=min(tempmin,root->val);
return true;
}
};