Problem
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.
A single node tree is a BST
Example
An example:
2
/ \
1 4
/ \
3 5
The above binary tree is serialized as {2,1,4,#,#,3,5}
(in level order).
Note
本文有两种DFS方法。
先看第一种,先跑左子树的DFS:如果不满足,返回false
。在左子树分支判断完成后,pre = root.left
(为什么?因为唯一给pre
赋值的语句是pre = root
,所以运行完dfs(root.left)
之后,pre = root.left
)。
然后,若pre.val
,也就是root.left.val
,大于等于root.val
的话,不满足BST定义,也返回false
;否则,继续执行pre = root
,(呐,现在去判断root.right
了,所以用root.val
和root.right.val
比较。)不满足就返回false
。
如果跑完了右子树的DFS,还没有返回false
,耶,返回true
,大功告成。
第二种DFS,用root
的值给左右子树的递归设定边界,注意,要用long
型的最大值和最小值哦!
Solution
DFS I
public class Solution {
TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
return dfs(root);
}
public boolean dfs(TreeNode root) {
if (root == null) return true;
if (!dfs(root.left)) return false;
if (pre != null && pre.val >= root.val) return false;
pre = root;
if (!dfs(root.right)) return false;
return true;
}
}
DFS II
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean dfs(TreeNode root, long min, long max) {
if (root == null) return true;
if (root.val <= min || root.val >= max) return false;
return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
}
}