leetcode: Validate Binary Search Tree

来源:互联网 发布:sql默认值 编辑:程序博客网 时间:2024/03/29 03:05

检查BST是否正确。需要注意的是每一个节点不光和其父节点有左右子的关系,和父节点的祖先节点还可能存在左右子的关系。那么在判断的时候,每个节点都有上界和下届两个判别因子。我们从根节点递归递归向下,每个左子结点的上界肯定是其父节点,下届需要我们从根节点传值下去不断更新,而该左子结点父节点的值也决定了该左子结点子节点中右子结点的上界;同理右子结点的上下界也是如此。


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isValidBST(TreeNode root) {        if( root == null )        {            return true;        }        return fun(root,99999,-99999);    }    boolean fun(TreeNode root,int lMax,int rMin)    {        boolean bl = true,br=true,Is=true;        if( root.left != null )        {            if( root.left.val >= root.val || root.left.val <= rMin )            {                Is = false;            }            int tmp = lMax;            if( root.val < tmp )            {                tmp = root.val;            }            bl = fun(root.left,tmp,rMin);        }        if( root.right != null )        {            if( root.right.val <= root.val || root.right.val >= lMax)            {                Is = false;            }            int tmp = rMin;            if( root.val > tmp )            {                tmp = root.val;            }            br = fun(root.right,lMax,tmp);        }        return bl&&br&&Is;    }}


0 0
原创粉丝点击