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:如果不满足,返回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
的值给左右子树的递归设定边界。
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
class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root, null, null);
}
private boolean isValid(TreeNode node, Integer min, Integer max) {
if (node == null) return true;
if (min != null && node.val <= min) return false;
if (max != null && node.val >= max) return false;
return isValid(node.left, min, node.val) && isValid(node.right, node.val, max);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。