Validate Binary Search Tree
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.
分析:方法一:根据二叉搜索树的定义,左子树的所有值小于根,右子树的所有值大于根。注意“所有”,不能简单判定左孩子< root->val <右孩子。利用两个值上下限定,保证左右子树的值均满足条件。如下图中的树, MIN < 8 <MAX ,8的左孩子:MIN<3<8 ,3的右孩子: 3<6<8,依次递归下去。
方法二:中序遍历,BST的中序遍历是有序的,如果前一个访问的节点大于后一个点,则不是bst。
代码:
/**
* 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) {
if(root==NULL) return true;
int left=INT_MIN,right=INT_MAX;//左右限定
return helper(root,left,right);
}
bool helper(TreeNode *root, int &left, int &right){
if(root==NULL) return true;
if(left<root->val && root->val < right){//当前节点的左右孩子满足条件
//root左子树的所有值都在(left,root->val)之间
return helper(root->left,left,root->val)&&helper(root->right,root->val,right);
}
return false;
}
};