面試題 04.05. 合法二叉搜索樹

實現一個函數,檢查一棵二叉樹是否爲二叉搜索樹。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    long last = LONG_MIN;
    bool isValidBST(TreeNode* root) {
        if(root == NULL)
            return true;
        if(!isValidBST(root->left))
            return false;
        if(last >= root->val)
            return false;
        last = root->val;
        if(!isValidBST(root->right))
            return false;
        return true;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return check(root,LONG_MIN,LONG_MAX);
    }
    bool check(TreeNode* root,long min,long max)
    {
        if(root == NULL)
            return true;
        if(root->val <= min || root->val >= max)
            return false;
        if(!check(root->left,min,root->val) || !check(root->right,root->val,max))
            return false;
        return true;
    }
    
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章