[leedcode 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.
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            //[2147483647]
            //注意,因为root的val是int型的,其可能为最大值或最小值,因此一开始的设置最大或最小要使用long型,注意函数参数的类型
            //本题非常巧妙使用最大值和最小值限制根节点的范围。最关键是对isvalid的正确定义,代表root的值是否在min和max中间
            
            //本题另一个解法是:将二叉树中序遍历,然后检测是否是递增数组
            return isvalid(root,(long)Integer.MIN_VALUE-1,(long)Integer.MAX_VALUE+1);
        }
        public boolean isvalid(TreeNode root,long min,long max){
            if(root==null){
                return true;
            }
            long val=(long)root.val;
            if(val>min&&val<max){
                return isvalid(root.left,min,val)&&isvalid(root.right,val,max);
            }else return false;
        }
    }

     

posted @ 2015-07-16 22:17  ~每天进步一点点~  阅读(122)  评论(0编辑  收藏  举报