題目
給定一個二叉樹淘讥,判斷它是否是合法的二叉查找樹(BST)
一棵BST定義為:
- 節(jié)點(diǎn)的左子樹中的值要嚴(yán)格小于該節(jié)點(diǎn)的值疚鲤。
- 節(jié)點(diǎn)的右子樹中的值要嚴(yán)格大于該節(jié)點(diǎn)的值梧却。
- 左右子樹也必須是二叉查找樹样刷。
- 一個節(jié)點(diǎn)的樹也是二叉查找樹。
樣例
一個例子:
2
/
1 4
/
3 5
上述這棵二叉樹序列化為 {2,1,4,#,#,3,5}.
分析
我們可以設(shè)置上下bound暴构,遞歸左右子樹時慷嗜,為它們設(shè)置最大值,最小值丹壕,并且不可以超過。
注意:下一層遞歸時薇溃,需要把本層的up 或是down繼續(xù)傳遞下去菌赖。相當(dāng)巧妙的算法。
代碼
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
public boolean isValidBST(TreeNode root) {
// Just use the inOrder traversal to solve the problem.
if (root == null) {
return true;
}
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private 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);
}
}