Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
37 lines (30 sloc) 1.25 KB
problem:
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.
----------------------------------------------------------------------------------------
solution:
//对每个结点,判断其值是否在左右界中,并实时更新界,
//比如遍历到根节点的左孩子结点,它的上界是根节点的值;遍历到根节点的右孩子结点,它的下界是根节点的值
/////////////////////////////////////
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isValidBST_aux(TreeNode *node, int leftVal, int rightVal)
{
if(node == NULL)
return true;
return leftVal < node->val && rightVal > node->val &&
isValidBST_aux(node->left, leftVal, node->val) &&
isValidBST_aux(node->right, node->val, rightVal);
}
bool isValidBST(TreeNode *root)
{
return isValidBST_aux(root, INT_MIN, INT_MAX);
}