leetcode 【每日一题】98. 验证二叉搜索树 Java

我的leetcode代码都已经上传到我的githttps://github.com/ragezor/leetcode

题干

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

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

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

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

示例 2:

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

想法

的问题一律递归。
写一个递归函数,判断节点值是否在左右之间。
看代码就ok
当然这道题还有另外一种解法:中序遍历

Java代码

package daily;

public class IsValidBST {
    public static class TreeNode {
     int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
 }

        public boolean helper(TreeNode node, Integer lower, Integer upper) {
            if (node == null) return true;

            int val = node.val;
            if (lower != null && val <= lower) return false;
            if (upper != null && val >= upper) return false;

            if (! helper(node.right, val, upper)) return false;
            if (! helper(node.left, lower, val)) return false;
            return true;
        }

        public boolean isValidBST(TreeNode root) {
            return helper(root, null, null);
        }
    


    public static  void main(String[] args){
        IsValidBST isValidBST =new IsValidBST();
        TreeNode root=new TreeNode(5);
        root.left= new TreeNode(1);
        root.right=new TreeNode(4);
        root.right.left=new TreeNode(3);
        root.right.right=new TreeNode(6);
        System.out.println(isValidBST.isValidBST(root));

    }

}

我的leetcode代码都已经上传到我的githttps://github.com/ragezor/leetcode

你可能感兴趣的:(leetcode刷题)