验证二叉搜索树

2019-12-21  本文已影响0人  二进制的二哈

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

递归解法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        return valid(root,Integer.MIN_VALUE,root.val-1,root.val+1,Integer.MAX_VALUE);
    }

    private boolean valid(TreeNode root,Integer minMin,Integer minMax,Integer maxMin,Integer maxMax){
        if (root == null)
            return true;
        if (root.val == Integer.MAX_VALUE && root.right != null)
            return false;
        if (root.val == Integer.MIN_VALUE && root.left != null)
            return false;
        TreeNode left = root.left;
        TreeNode right = root.right;
        if ((left == null || (left.val <= minMax && left.val >= minMin )) && (right == null || (right.val <= maxMax && right.val >= maxMin ))){
            if (left != null){
                if (!valid(left,minMin,left.val - 1,left.val + 1,root.val-1))
                    return false;
            }
            if (right != null){
                return valid(right,root.val+1,right.val - 1,root.val + 1,maxMax);
            }
            return true;
        }
        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读