Validate Binary Search Tree
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
An example:
2
/ \
1 3
/
4
\
5
The above binary tree is serialized as {2,1,3,#,#,4,#,#,5}
(in level order).
SOLUTION 1:
首先想到中序遍历,由于BST的特殊,所以BST的中序遍历一定是升序的,所以只要考虑遍历的前一个点pre的值是否比现在的值大,就可以判断了。
再往局部去想,就是如果有左儿子的时候,那么左儿子的值一定小于root的值才能满足条件。
代码如下
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
private TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if (root == null){
return true;
}
//判断左边是不是
if (!isValidBST(root.left)){
return false;
}
//判断左边整个树跟root这一段是不是
if (pre != null && pre.val >= root.val){
return false;
}
//判断右边是不是
pre = root;
if (!isValidBST(root.right)){
return false;
}
return true;
}
}
SOLUTION 2:
Divide & Conquer 分治法:
首先分析这个题需要用到参数都有哪些:当前值跟左右两边儿子值的关系,以及返回值是否是BST。在考虑当前值跟左右儿子值的大小关系的时候呢,不必考虑所有儿子的值的大小,只需要找到他们最大值跟最小值就可以进行比较了,所以要用到的参数就变成了:左右子树的minValue, maxValue,以及返回值isBST。于是定义一个ResultType,并且里面三个参数,min值,max值,是否是BST。
在做递归时候呢,我的想法呢,是先不考虑那些中止条件,先假设都是没问题的考虑这个时候不断递归返回的是什么,要把什么值传到下一层去。
在这个题里呢,每一层递归都要先Divide,right 和 left,然后再用Conquer思想归并一下结果传入下一层去。
现在来考虑终止条件,根据题意,1,左子树,右子树有一个不是BST,整个树就不是BST,返回false同时,min max值都归0就可以了,因为返回false就中止了。2,左子树和右子树是BST但是左子树最大值大于root值,或者右子树最小值小于root值。
注意,在处理非法输入时候,如果本身需要最大值,处理边界条件时候就要保留最小值,反之,需要最小值就返回最大值,这样是避免输入非法时候的返回值成为最后结果的最优值。
具体实现看code:
class ResultType{
int minValue;
int maxValue;
boolean isBST;
ResultType(boolean isBST, int minValue, int maxValue){
this.isBST = isBST;
this.minValue = minValue;
this.maxValue = maxValue;
}
}
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) {
ResultType result = helper(root);
return result.isBST;
}
private ResultType helper(TreeNode root){
if (root == null){
return new ResultType(true, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
//Divide部分
ResultType left = helper(root.left);
ResultType right = helper(root.right);
//中止条件
if (!left.isBST || !right.isBST){
//结果时false的话,min max值都无所谓了
return new ResultType(false, 0, 0);
}
if (root.left != null && left.maxValue >= root.val || root.right != null && right.minValue <= root.val){
return new ResultType(false, 0, 0);
}
//Conquer 部分:把最大值最小值传到下一层去
return new ResultType(true, Math.min(root.val, left.minValue), Math.max(root.val, right.maxValue));
}
}