98. Validate Binary Search Tree

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.

思路:
验证二叉搜索树,第一次做的时候以为就是验证parent节点的值大于其left child,小于其right child的值,后来发现自己写出来的代码是错误的。 原因是这样的毕竟只能保证parent节点跟direct left和direct right节点的关系, 并不能保证跟left substree跟right subtree的关系满足二叉搜索树的要求。 所以这里我们验证的是: parent节点的值应该大于左子树节点的值,小于右子树节点的值>

public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        return validate(root, Long.MAX_VALUE, Long.MIN_VALUE);
    }

    public boolean validate(TreeNode root, long max, long min) {
        if (root == null) return true;
        if (root.val >= max || root.val <= min) {
            return false;
        }
        return validate(root.left, root.val, min) && validate(root.right, max, root.val);
    }
}

我们还可以用in-order traversal的方式来验证这个树是ascending order的, 比较前一个节点(pre)跟当前节点(cur)的关系,满足pre.val < cur.val:
针对每个节点我们可以用以下recursion:
验证left-subtree
比较当前节点值跟pre节点值。
验证right-subtree

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s