2015年10月2日星期五

Leetcode 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.
Solution 1: Use node as low and high limit instead of use Integer.MAX_VALUE and Integer.MIN_VALUE.
 public class Solution {  
   public boolean isValidBST(TreeNode root) {  
     return dfs(root,null,null);  
   }  
   private boolean dfs(TreeNode x, TreeNode l, TreeNode r) {  
     if (x==null) return true;  
     if (l!=null && l.val>=x.val) return false;  
     if (r!=null && r.val<=x.val) return false;  
     return dfs(x.left,l,x) && dfs(x.right,x,r);  
   }  
 }  

没有评论:

发表评论