您的位置:首页 > 其它

Validate Binary Search Tree

2015-08-07 08:41 274 查看
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.
关键算法:All values on the left sub tree must be less than root, and all values on the right sub tree must be greater than root. So we just check the boundaries for each node.

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool helper(TreeNode* root, long int mini, long int maxi)
{
if(root == NULL)
{
return true;
}
if(root -> val <= mini || root -> val >= maxi)
{
return false;
}
return helper(root -> left, mini, root -> val) && helper(root -> right, root -> val, maxi);

}

bool isValidBST(TreeNode* root)
{
if(root == NULL)
{
return true;
}
if(root -> left == NULL && root -> right == NULL)
{
return true;
}
// if (root -> val == 2147483647 && root -> left != NULL
//     && root -> left -> val == -2147483648 && root -> right == NULL)
// {
//     return true;
// }

return helper(root, -2147483649, 2147483648);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: