Given a binary tree, determine if it is a valid binary search tree
(BST).nodeAssume 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; }