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.
设置一个最大和最小值,同时更新。
public class Solution { //Time: O(n) public boolean isValidBST(TreeNode root) { return isValid(root, Integer.MAX_VALUE, Integer.MIN_VALUE); } private boolean isValid(TreeNode root, int max, int min) { if (root == null) { return true; } if (root.val >= max || root.val <= min) { return false; } return isValid(root.left, root.val, min) && isValid(root.right, max, root.val); } }
用类似一个inorder的方法,灵感来自recover BST。
public class Solution { private TreeNode last = null; public boolean isValidBST(TreeNode root) { if (root == null) { return true; } boolean left = isValidBST(root.left); if (last != null && last.val >= root.val) { return false; } last = root; boolean right = isValidBST(root.right); return left && right; } }
No comments:
Post a Comment