98. 驗證二叉搜索樹(Validate Binary Search Tree)

給定一個二叉樹,判斷其是否是一個有效的二叉搜索樹。

假設一個二叉搜索樹具有如下特徵:

節點的左子樹只包含小於當前節點的數。
節點的右子樹只包含大於當前節點的數。
所有左子樹和右子樹自身必須也是二叉搜索樹。
示例 1:

輸入:
    2
   / \
  1   3
輸出: true
示例 2:

輸入:
    5
   / \
  1   4
     / \
    3   6
輸出: false
解釋: 輸入爲: [5,1,4,null,null,3,6]。
     根節點的值爲 5 ,但是其右子節點值爲 4 。


中序遍歷,判斷是否有序

/**
 * 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 {
    void inorder(TreeNode* root)
    {
        if(root==NULL)
            return;
        inorder(root->left);
        res.push_back(root->val);
        inorder(root->right);
        
    }
    vector<int>res;
public:
    bool isValidBST(TreeNode* root) {
        if (root==NULL)
            return true;
        //中序遍歷以root爲根的二叉樹
        inorder(root);
        //判斷是否有序
        for(int i=0;i<res.size()-1;i++)
        {
            if(res[i]>=res[i+1])
                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 {
    void inorder(TreeNode* root,vector<int>&res)
    {
        if(root==NULL)
            return;
        inorder(root->left,res);
        res.push_back(root->val);
        inorder(root->right,res);
        
    }
    
public:
    bool isValidBST(TreeNode* root) {
        if (root==NULL)
            return true;
        vector<int>res;
        //中序遍歷以root爲根的二叉樹
        inorder(root,res);
        //判斷是否有序
        for(int i=0;i<res.size()-1;i++)
        {
            if(res[i]>=res[i+1])
                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) {
        TreeNode* min = NULL;
        TreeNode* max = NULL;
        return isValidBST_helper(root, min, max);
    }
    
    bool isValidBST_helper(TreeNode* root, TreeNode* min, TreeNode* max)
    {
        if(root == NULL)
        {
            return true;
        }
        if(min != NULL && root->val <= min->val)
        {
            return false;
        }
        if(max != NULL && root->val >= max->val)
        {
            return false;
        }
        
        return isValidBST_helper(root->left, min, root) && 
               isValidBST_helper(root->right, root, max );
    }
};

 

 

 

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