LeetCode :: Validate Binary Search Tree[詳細分析],leetcodevalidate

來源:互聯網
上載者:User

LeetCode :: Validate Binary Search Tree[詳細分析],leetcodevalidate


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.
回顧一下BST的定義,任一節點的子孫分別遞迴滿足,左子孫小於該節點,右子孫大於該節點;只要判斷這個就OK了;一個主意點:在遞迴程式裡面,僅判斷一個節點大於左兒子小於右兒子是不夠的,這樣對於左兒子的右兒子以及右兒子的左兒子的錯誤判斷不到,因此需要將節點值變為邊界值,遞迴下傳;代碼如下:
class Solution {public:    bool isValidBST(TreeNode *root) {        return check(root, INT_MIN, INT_MAX);    }    private:    bool check(TreeNode *root, int left, int right){        if(root == NULL)            return true;        return (root->val > left) && (root->val < right)                && check(root->left, left, root->val) &&check(root->right, root->val, right);     }//這裡的左兒子的左界用上面傳下來的,右界用節點值,右兒子鏡面對稱};

PS:按照注意點提到的思路寫的錯誤碼
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isValidBST(TreeNode *root) {        if (root == NULL)            return true;                    bool bleft = true, bright = true;        if (root->left != NULL){            if (root->val > root->left->val){    //注意這裡檢驗以及遞迴是不能保證根節點大於左邊所有的,矛盾在於,左兒子的右兒子,以及右兒子的左兒子;                bleft = isValidBST(root->left);            }            else{                return false;            }        }                if (root->right != NULL){            if (root->val < root->right->val){                bright = isValidBST(root->right);            }            else{                return false;            }        }        return bleft && bright;    }};






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.