您的位置:首页 > 其它

95 - 验证二叉查找树

2017-09-29 17:37 274 查看
2017.9.29

刚开始想采用递归的方法,先判断根和左节点右节点的关系,在判断左子树和右子树是不是查找树。

然而这种想法逻辑上其实是错误的。 比如

             10

          /         \

        2           15

    /      \        /     \

1         11    9      17

这颗二叉树单独看根节点和左右节点满足查找树的条件,左子树和右子树也满足条件,但是整棵树并不是二叉查找树。

还是采用中序遍历的方法,看数是不是严格单调递增的。

在这里有一个问题就是初始设置了一个pre为Integer.Min,但是忽略了根节点是可以等于这个值得,就很草率的采用 大于号直接判断了。

其实应该对第一个点的值进行特殊处理的,所以加入了一个first来标识。

/**
* 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) {
if(root == null ||(root.right == null && root.left == null)){
return true;
}
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode bt = root;
boolean first = false;
int pre = Integer.MIN_VALUE;
while(bt != null ||!stack.isEmpty()){
while(bt != null){
stack.push(bt);
bt = bt.left;
}
if(!stack.isEmpty()){
int tmp = stack.peek().val;
if(tmp <= pre && first == true){
return false;
}
first = true;
pre = tmp;
bt = stack.pop();
bt = bt.right;
}
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: