Problem Description:
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
解法一:
二叉搜索树定义为或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
因此直接采用遍历判断的方法,每次找到该节点左子树的最大值和右子树的最小值与当前节点比较,不满足条件则不是,满足再判断左右子树是否都满足条件。该解法最坏情况复杂度为O(n^2)。(最坏情况为所有结点都在一边的时候)
代码如下:
/**
* 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)
return true;
if(root->left)
{
TreeNode *p=root->left;
while(p->right)
p=p->right;
if(p->val>=root->val)
return false;
}
if(root->right)
{
TreeNode *p=root->right;
while(p->left)
p=p->left;
if(p->val<=root->val)
return false;
}
return isValidBST(root->left)&&isValidBST(root->right);
}
};
解法二:
利用二叉搜索树中序遍历有序递增的性质,在中序遍历的过程中判断左子树、当前节点和右子树是否满足条件,时间复杂度为O(n)。
代码如下:
/**
* 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 IsBST(TreeNode* root, int &pre) {
if (root == NULL) return true;
if (IsBST(root->left,pre))
{
if(root->val>pre)//判断当前结点值是否大于prev,此时prev为中序遍历时当前结点的前一个值。
{ pre=root->val;
return IsBST(root->right,pre);
}
else
return false;
}
else
return false;
}
bool isValidBST(TreeNode* root) {
int pre=INT_MIN;
return IsBST(root, pre);
}
};