1. 程式人生 > >leetcode98 驗證二叉搜尋樹

leetcode98 驗證二叉搜尋樹

給定一個二叉樹,判斷其是否是一個有效的二叉搜尋樹。

假設一個二叉搜尋樹具有如下特徵:

  • 節點的左子樹只包含小於當前節點的數。
  • 節點的右子樹只包含大於當前節點的數。
  • 所有左子樹和右子樹自身必須也是二叉搜尋樹。

示例 1:

輸入:
    2
   / \
  1   3
輸出: true

示例 2:

輸入:
    5
   / \
  1   4
     / \
    3   6
輸出: false
解釋: 輸入為: [5,1,4,null,null,3,6]。
     根節點的值為 5 ,但是其右子節點值為 4 。

解法1:可以利用它本身的性質來做,即左<根<右

public boolean isValidBST(TreeNode root) {
    if(root == null) return true;
    return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean valid(TreeNode root, long low, long high){
    if(root == null) return true;
    if(root.val <= low || root.val >= high) return false;
    return valid(root.left, low, root.val) && valid(root.right, root.val, high);
}

解法2:利用中序遍歷結果為有序數列來做

public boolean isValidBST(TreeNode root) {
    if(root == null) return true;
    List<Integer> list = new ArrayList<>();
    inOrder(root, list);
    for(int i = 0; i < list.size() - 1; i++){
        if(list.get(i) >= list.get(i + 1)){
            return false;
        }
    }
    return true;
}
public void inOrder(TreeNode root, List<Integer> list){
    if(root == null) return;
    inOrder(root.left, list);
    list.add(root.val);
    inOrder(root.right, list);
}