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.

根据BST的定义进行判断即可。注意:左子树的所有节点都小于根节点,右子树的所有节点都大于根节点。

因此这种判断方式是错误的。

 1 public class Solution {
 2     public boolean isValidBST(TreeNode root) {
 3         if (root == null) {
 4             return true;
 5         }
 6 
 7         if (root.left != null && !(root.left.val) < root.val) {
 8             return false;
 9         }
10         if (root.right != null && !(root.right.val) > root.val) {
11             return false;
12         }
13         return isValidBST(root.left) && isValidBST(root.right);
14     }
15 }

 这个算法没有考虑到左子树的所有节点都小于根节点,右子树的所有节点都大于根节点。它只考虑了左孩子节点小于其父亲节点,右孩子节点大于其父亲节

如:         

          2
        / \
        1     4
           \  /  \
         6  3    5

对于左子树中的右孩子节点,它要大于其父亲节点又要小于其所在左子树的根节点。

对于右子树中的左孩子节点,它要小于其父亲节点又要大于其所在右子树的根节点。

因此往左走时,其父亲节点为最大值,往右走时其父节点为最小值。

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isValidBST(TreeNode root) {
12         if (root == null) {
13             return true;
14         }
15         return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
16     }
17     
18     private boolean isValidBST(TreeNode root, long min, long max) {
19         if (root == null) {
20             return true;
21         }
22         if (root.val <= min || root.val >= max) {
23             return false;
24         }
25         return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
26     }
27 }

 

                     

posted @ 2016-03-15 09:03  YuriFLAG  阅读(93)  评论(0)    收藏  举报