98. Validate Binary Search Tree
- Total Accepted: 151797
- Total Submissions: 665772
- Difficulty: Medium
- Contributor: LeetCode
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.
解題思路:一開始想到的是中序遍歷,然後將遍歷到所有節點的val值壓到vector中,最後對vector進行遍歷判斷是否爲嚴格升序,但是這個方法實現起來太複雜(或者說是太不優美),於是繼續想了想應該用遞歸可以直接判斷,這裏有一個難點是如何判斷子節點與祖父節點之間的大小(也就是所謂的僞BST樹),這裏用的辦法是新使用一個函數judge(新加參數min,max來保存祖父節點的val值)。
class Solution {
public:
bool isValidBST(TreeNode* root) {
return Judge(root, -2147483648, 2147483647);
}
bool Judge(TreeNode* root,int min,int max)
{
if(root==NULL)
return true;
if(root->val < min || root->val > max){
return false;
}
else if(root->left&&root->right)
{
//cout<<1<<endl;
if(root->left->val < root->val && root->right->val > root->val){
return Judge(root->left, min, root->val-1) && Judge(root->right, root->val+1, max);
}else{
return false;
}
}
else if(root->left!=NULL)
{
//cout<<2<<endl;
return (root->val>root->left->val)&&Judge(root->left,min,root->val-1);
}
else if(root->right!=NULL)
{
//cout<<3<<endl;
return(root->val<root->right->val)&&Judge(root->right,root->val+1,max);
}
else
return true;
}
};