您的位置:首页 > 其它

[LeetCode] Validate binary search tree

2013-03-23 03:11 351 查看
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.

My code: set the limits for the maximum value and minimum value for a child tree."Leaf to Root approach"

class Solution {
public:
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int leftmost,rightmost;
return helper(root,leftmost,rightmost);
}

bool helper(TreeNode *root, int &leftmost, int &rightmost){

if(root==NULL)
{
leftmost=rightmost=0;
return true;
}

int leftleftmost,leftrightmost,rightleftmost,rightrightmost;
int childrenresult=helper(root->left,leftleftmost,leftrightmost)*helper(root->right,rightleftmost,rightrightmost);

leftmost=leftleftmost;
rightmost=rightrightmost;
if(root->left==NULL)
{
leftmost=root->val;
}
if(root->right==NULL)
{
rightmost=root->val;
}

if(childrenresult==0)
{
return false;
}
if(root->left!=NULL && (root->left->val >= root->val || leftrightmost >= root->val))
{
return false;
}
if(root->right!=NULL && (root->right->val <= root->val || rightleftmost <= root->val))
{
return false;
}
return true;
}
};

http://fisherlei.blogspot.com/2013/01/leetcode-validate-binary-search-tree.html

The same idea, BUT "root to leaf approach", his code is much much more concise!!!!

class Solution {
public:
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return helper(root,INT_MIN,INT_MAX); //INT_MIN and INT_MAX are the minimum and maximum number presented by integer type
}

bool helper(TreeNode *root, int min, int max){
if(root==NULL)
{
return true;
}

if(root->val > min && root->val<max
&& helper(root->left,min,root->val)
&& helper(root->right,root->val,max))
return true;
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: