1. 程式人生 > >[LeetCode] Validate Binary Search Tree 驗證二叉搜尋樹

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

這道驗證二叉搜尋樹有很多種解法,可以利用它本身的性質來做,即左<根<右,也可以通過利用中序遍歷結果為有序數列來做,下面我們先來看最簡單的一種,就是利用其本身性質來做,初始化時帶入系統最大值和最小值,在遞迴過程中換成它們自己的節點值,用long代替int就是為了包括int的邊界條件,程式碼如下:

C++ 解法一:

// Recursion without inorder traversal
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        return isValidBST(root, LONG_MIN, LONG_MAX);
    }
    
bool isValidBST(TreeNode *root, long mn, long mx) { if (!root) return true; if (root->val <= mn || root->val >= mx) return false; return isValidBST(root->left, mn, root->val) && isValidBST(root->right, root->val, mx); } };

Java 解法一:

public class Solution {
    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);
    }
}

這題實際上簡化了難度,因為一般的二叉搜尋樹是左<=根<右,而這道題設定為左<根<右,那麼就可以用中序遍歷來做。因為如果不去掉左=根這個條件的話,那麼下邊兩個數用中序遍歷無法區分:

   20       20
   /           \
 20           20

它們的中序遍歷結果都一樣,但是左邊的是BST,右邊的不是BST。去掉等號的條件則相當於去掉了這種限制條件。下面我們來看使用中序遍歷來做,這種方法思路很直接,通過中序遍歷將所有的節點值存到一個數組裡,然後再來判斷這個陣列是不是有序的,程式碼如下:

C++ 解法二:

// Recursion
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        if (!root) return true;
        vector<int> vals;
        inorder(root, vals);
        for (int i = 0; i < vals.size() - 1; ++i) {
            if (vals[i] >= vals[i + 1]) return false;
        }
        return true;
    }
    void inorder(TreeNode *root, vector<int> &vals) {
        if (!root) return;
        inorder(root->left, vals);
        vals.push_back(root->val);
        inorder(root->right, vals);
    }
};

Java 解法二:

public class Solution {
    public boolean isValidBST(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        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 node, List<Integer> list) {
        if (node == null) return;
        inorder(node.left, list);
        list.add(node.val);
        inorder(node.right, list);
    }
}

下面這種解法跟上面那個很類似,都是用遞迴的中序遍歷,但不同之處是不將遍歷結果存入一個數組遍歷完成再比較,而是每當遍歷到一個新節點時和其上一個節點比較,如果不大於上一個節點那麼則返回false,全部遍歷完成後返回true。程式碼如下:

C++ 解法三:

// Still recursion
class Solution {
public:
    TreeNode *pre;
    bool isValidBST(TreeNode *root) {
        int res = 1;
        pre = NULL;
        inorder(root, res);
        if (res == 1) return true;
        else false;
    }
    void inorder(TreeNode *root, int &res) {
        if (!root) return;
        inorder(root->left, res);
        if (!pre) pre = root;
        else {
            if (root->val <= pre->val) res = 0;
            pre = root;
        }
        inorder(root->right, res);
    }
};

當然這道題也可以用非遞迴來做,需要用到棧,因為中序遍歷可以非遞迴來實現,所以只要在其上面稍加改動便可,程式碼如下:

C++ 解法四:

// Non-recursion with stack
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode *p = root, *pre = NULL;
        while (p || !s.empty()) {
            while (p) {
                s.push(p);
                p = p->left;
            }
            TreeNode *t = s.top(); s.pop();
            if (pre && t->val <= pre->val) return false;
            pre = t;
            p = t->right;
        }
        return true;
    }
};

Java 解法四:

public class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode p = root, pre = null;
        while (p != null || !s.empty()) {
            while (p != null) {
                s.push(p);
                p = p.left;
            }
            TreeNode t = s.pop();
            if (pre != null && t.val <= pre.val) return false;
            pre = t;
            p = t.right;
        }
        return true;
    }
}

最後還有一種方法,由於中序遍歷還有非遞迴且無棧的實現方法,稱之為Morris遍歷,可以參考我之前的部落格 Binary Tree Inorder Traversal,這種實現方法雖然寫起來比遞迴版本要複雜的多,但是好處在於是O(1)空間複雜度,參見程式碼如下:

C++ 解法五:

class Solution {
public:
    bool isValidBST(TreeNode *root) {
        if (!root) return true;
        TreeNode *cur = root, *pre, *parent = NULL;
        bool res = true;
        while (cur) {
            if (!cur->left) {
                if (parent && parent->val >= cur->val) res = false;
                parent = cur;
                cur = cur->right;
            } else {
                pre = cur->left;
                while (pre->right && pre->right != cur) pre = pre->right;
                if (!pre->right) {
                    pre->right = cur;
                    cur = cur->left;
                } else {
                    pre->right = NULL;
                    if (parent->val >= cur->val) res = false;
                    parent = cur;
                    cur = cur->right;
                }
            }
        }
        return res;
    }
};

類似題目:

參考資料: