标签:大小 validate 来源 http btree 个数 bool binary 比较
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.
Example 1:
2
/ 1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ 2 3
Binary tree [1,2,3], return false.
class Solution_98 {
public:
//bug
bool isValidBST_bug(TreeNode* root) {
if (!root||(!root->right&&!root->left))
{
return true;
}
if (root->left!=NULL&&root->left->val>=root->val)
{
return false;
}
if (root->right!=NULL&&root->right->val<=root->val)
{
return false;
}
return isValidBST_bug(root->left) && isValidBST_bug(root->right);
}
// 二分查找树的中序遍历结果是一个递增序列
TreeNode* pre = NULL;
void InOrder(TreeNode* root,int &res)
{
if (!root)
{
return;
}
InOrder(root->left, res);
if (!pre)
{
pre = root;
}
else
{
if (root->val<=pre->val)
{
res = 0;
}
pre = root;
}
InOrder(root->right,res);
return;
}
bool isValidBST(TreeNode *root) {
if (!root)
{
return true;
}
int res = 1;
InOrder(root,res);
if (res==0)
{
return false;
}
return true;
}
};
98. Validate Binary Search Tree
标签:大小 validate 来源 http btree 个数 bool binary 比较
原文地址:https://www.cnblogs.com/ranjiewen/p/8831998.html