【LeetCode】98. 验证二叉搜索树(JAVA)

原题地址: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;
        Stack<TreeNode> s = new Stack<>();
        TreeNode tmp = root;
        Integer num = null;
        while(!s.isEmpty() || root != null)
        {
            while(root != null)
            {
                s.push(root);
                root = root.left;
            }
            root = s.pop();
            if(num != null && num >= root.val) return false;
            num = root.val;
            root = root.right;
        }
        return true;
    }
}
//递归
/**
 * 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) {
        return isValid(root, null, null);
    }

    public boolean isValid(TreeNode root, Integer low, Integer high)
    {
        if(root == null) return true;
        Integer num = root.val;
        if(low != null && low >= num) return false;
        if(high != null && high <= num) return false;

        return isValid(root.left, low, num) && isValid(root.right, num, high);
    }
}
发布了110 篇原创文章 · 获赞 4 · 访问量 9322

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104678850
今日推荐