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.

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 
BST如果进行inorder 的话应该是sorted。
 1 /**
 2  * Definition for binary tree
 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     int per = 0;
12     boolean sig;
13     public boolean isValidBST(TreeNode root) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         per = Integer.MIN_VALUE;
17         sig = true;
18         isValid(root);
19         return sig;
20     }
21     public void isValid(TreeNode root){
22         if(root == null) return;
23         isValid(root.left);
24         if(root.val > per) per = root.val;
25         else{
26             sig = false;
27             return;
28         }
29         isValid(root.right);
30     }
31 }

还是可以使用递归来做:

 1 public class Solution {
 2     public boolean isValidBST(TreeNode root) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         return root == null || check(root.left, Integer.MIN_VALUE, root.val) && check(root.right, root.val, Integer.MAX_VALUE);
 6     }
 7     public boolean check(TreeNode root, int min, int max){
 8         if(root == null) return true;
 9         if(!(min < root.val && root.val < max)) return false;
10         return check(root.left, min, root.val) && check(root.right, root.val, max);
11     }
12 }

这个方法很好!

posted on 2013-11-15 14:10  Step-BY-Step  阅读(139)  评论(0编辑  收藏  举报

导航