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

    2
   / \
  1   3

Binary tree [2,1,3], return true.
Example 2:

  1
 / \
2   3

Binary tree [1,2,3], return false.

解題思路:
本題要求驗證二叉樹是否是BST, 根據二叉樹中序遍歷的定義,如果是BST,則會得到一個升序的數組。利用中序遍歷可以判斷是否是BST, 只需保存前一個節點的地址。

代碼如下:

class Solution {
public:
    bool validateBST(TreeNode* root, TreeNode* &prev)
    {
        if(root == NULL)  return true;
        if(!validateBST(root->left,prev)) return false; //左子樹一直遍歷到底,然后最后一個葉節點變成prev,root向上回朔一個節點開始比較
        if(prev != NULL && root->val <= prev->val) return false; //比較prev和root的大小,注意不可以等于
        prev = root; //將root設為prev
        return validateBST(root->right,prev); //比較root->right和prev
    }

    bool isValidBST(TreeNode* root) {
        TreeNode* prev = NULL;
        return validateBST(root,prev);
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容