Validate Binary Search Tree leetcode

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

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.less

递归法

思路

遍历树, 用数组保存以前访问的节点, 若是以前访问的都小于当前访问的值那么树就是合理树code

复杂度

时间 O(n) 空间 递归栈O(log)递归

代码

public boolean isValidBST(TreeNode root) {
    if (root == null) {
        return true;
    }
    ArrayList<Integer> cur = new ArrayList<Integer>();
    cur.add(null);
    return helper(cur, root);
}
public boolean helper(ArrayList<Integer> cur, TreeNode root) {
    if (root == null) {
        return true;
    }
    boolean left = helper(cur, root.left);
    if (cur.get(0) != null) {
        if (cur.get(0) >= root.val) {
            return false;
        }
    }
    cur.set(0, root.val);
    
    boolean right = helper(cur, root.right);
    return left && right;
}
相关文章
相关标签/搜索