95 - 验证二叉查找树

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;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章