C++實現LeetCode(98.驗證二叉搜索樹)

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

Example 1:

Input:
2
/ \
1   3
Output: true

Example 2:

    5
/ \
1   4
/ \
3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node’s value
is 5 but its right child’s value is 4.

這道驗證二叉搜索樹有很多種解法,可以利用它本身的性質來做,即左<根<右,也可以通過利用中序遍歷結果為有序數列來做,下面我們先來看最簡單的一種,就是利用其本身性質來做,初始化時帶入系統最大值和最小值,在遞歸過程中換成它們自己的節點值,用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++ 解法三:

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

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

C++ 解法四:

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;
            }
            p = s.top(); s.pop();
            if (pre && p->val <= pre->val) return false;
            pre = p;
            p = p->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;
            }
            p = s.pop();
            if (pre != null && p.val <= pre.val) return false;
            pre = p;
            p = p.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;
    }
};

到此這篇關於C++實現LeetCode(98.驗證二叉搜索樹)的文章就介紹到這瞭,更多相關C++實現驗證二叉搜索樹內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: