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.
Example 1:
Binary tree [2,1,3]
, return true.
Example 2:
Binary tree [1,2,3]
, return false.
Solution
DFS, time O(n)
注意处理overflow!
eg: [-2147483648,-2147483648], return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
// take long as input to avoid overflow
public boolean isValidBST(TreeNode root, long min, long max) {
if (root == null) {
return true;
}
if (root.val < min || root.val > max) {
return false;
}
return isValidBST(root.left, min, root.val - 1l) // convert to long
&& isValidBST(root.right, root.val + 1l, max);
}
}
Inorder-traversal, time O(n), space O(n)
BST的inorder traversal是有序的!要谨记这个特性。用Stack来实现inorder traversal。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
// inorder traversal
TreeNode pre = null;
TreeNode curr = root;
Stack<TreeNode> stack = new Stack<>();
while (curr != null || !stack.empty()) {
while (curr != null) { // push all left nodes
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
if (pre != null && curr.val <= pre.val) {
return false;
}
pre = curr;
curr = curr.right;
}
return true;
}
}