Post

Validate Binary Search Tree

LeetCode https://leetcode.cn/problems/validate-binary-search-tree/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }

        return isBSTHelper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isBSTHelper(TreeNode root, long lo, long hi) {
        if (root == null) {
            return true;
        }
        if (root.val <= lo || root.val >= hi) {
            return false;
        }

        return isBSTHelper(root.left, lo, root.val) && isBSTHelper(root.right, root.val, hi);
    }
}

Complexity

  • Time = O(n)
  • Space = O(height)

这道题有一个测试用例 [2147483647] 如果边界范围不够大,这个用例过不了。。。

This post is licensed under CC BY 4.0 by the author.