来源

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

描述

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

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

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

题解

递归法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public boolean helper(TreeNode node, Integer lower, Integer upper) {
  12. if (node == null) return true;
  13. int val = node.val;
  14. if (lower != null && node.val <= lower) return false;
  15. if (upper != null && node.val >= upper) return false;
  16. if (!helper(node.left, lower, val)) return false;
  17. if (!helper(node.right, val, upper)) return false;
  18. return true;
  19. }
  20. public boolean isValidBST(TreeNode root) {
  21. return helper(root, null, null);
  22. }
  23. }
  • 时间复杂度 : 98. 验证二叉搜索树(Validate Binary Search Tree) - 图1。每个结点访问一次。
  • 空间复杂度 : 98. 验证二叉搜索树(Validate Binary Search Tree) - 图2。我们跟进了整棵树。

中序遍历

class Solution {
    public boolean isValidBST(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        Integer inorder = null;

        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }

            root = stack.pollLast();
            if (inorder != null && root.val <= inorder) {
                return false;
            }
            inorder = root.val;

            root = root.right;
        }

        return true;
    }
}

复杂度分析

  • 时间复杂度 : 98. 验证二叉搜索树(Validate Binary Search Tree) - 图3,最坏情况下: 树为二叉搜索树或破坏条件的元素是最右叶结点
  • 空间复杂度 : 98. 验证二叉搜索树(Validate Binary Search Tree) - 图4,用于存储 stack