98. Validate Binary Search Tree

https://leetcode.com/problems/validate-binary-search-tree/description/

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

Thoughts

检验给定BST是否合法。BST进行中序遍历一定是升序的,利用此性质检查当前结点值是否>上个结点。

Code

class Solution {
    TreeNode prev = null;
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (!isValidBST(root.left) || prev != null && prev.val >= root.val) {
            return false;
        }
        prev = root;
        return isValidBST(root.right);
    }
}

Analysis

做题耗时 5min

时间复杂度同中序遍历,O(n)

Ver.2

Last updated

Was this helpful?