[LeetCode] - 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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

經典binary tree的題目。用一個區間,初始化爲(min, max)。依次用它檢查樹中的每一點。如果在區間中,就是合理的。否則,返回false。對區間的更新遵守這樣的原則:如果是左子樹的遞歸,就更新max爲root.val;如果是右子樹遞歸,就更新min爲root.val。當然,也可以對樹進行中序遍歷,然後檢查得到的遍歷結果是不是有序的。但是這樣還需要額外的空間,肯定沒有用區間的方法好,就不再贅述了。

具體代碼如下:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBSTHelper(TreeNode root, int lowerBound, int upperBound) {
        if(root==null) return true;
        if(root.val>lowerBound && root.val<upperBound) {
            return isValidBSTHelper(root.left, lowerBound, root.val) && isValidBSTHelper(root.right, root.val, upperBound);
        }
        else return false;
    }
    
    public boolean isValidBST(TreeNode root) {
        return isValidBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
}


Version 2: Construct an array through in-order traversal. Determine whether this array is sorted or not. 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void isValidBST(TreeNode root, ArrayList<Integer> inorder) {
        if(root==null) return;
        isValidBST(root.left, inorder);
        inorder.add(root.val);
        isValidBST(root.right, inorder);
        return;
    }
    
    public boolean isValidBST(TreeNode root) {
        ArrayList<Integer> inorder = new ArrayList<Integer>();
        isValidBST(root, inorder);
        for(int i=0; i<inorder.size()-1; i++) {
            if(inorder.get(i)>=inorder.get(i+1)) return false;
        }
        return true;
    }
}

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