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


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