LeetCode - 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.

Solution 1:

 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 maxValue(TreeNode r){
12         if(r == null) return Integer.MIN_VALUE;
13         int left = maxValue(r.left);
14         int right = maxValue(r.right);
15         return Math.max(r.val, Math.max(left, right));
16     }
17     int minValue(TreeNode r){
18         if(r == null) return Integer.MAX_VALUE;
19         int left = minValue(r.left);
20         int right = minValue(r.right);
21         return Math.min(r.val, Math.min(left, right));
22     }
23     public boolean isValidBST(TreeNode root) {
24         // Start typing your Java solution below
25         // DO NOT write main() function
26         if(root == null) 
27             return true;
28         if(maxValue(root.left) >= root.val || minValue(root.right) <= root.val)
29             return false;
30         return (isValidBST(root.left) && isValidBST(root.right));
31     }
32 }

 

Solution 2:

 1 public class Solution {
 2     public boolean validate(TreeNode root, int min, int max){
 3         if(root == null)
 4             return true;
 5         if(root.val > min && root.val < max && 
 6             validate(root.left, min, root.val) &&
 7             validate(root.right, root.val, max))
 8             return true;
 9         else
10             return false;
11     }
12     public boolean isValidBST(TreeNode root) {
13         // Start typing your Java solution below
14         // DO NOT write main() function
15         return validate(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
16     }
17 }

 

posted @ 2013-01-27 13:17  cradle  阅读(615)  评论(0编辑  收藏  举报