leetcode98. 验证二叉搜索树

递归中序遍历,logn时间,但由于使用vector容器,空间复杂度O(n);

/**
 * 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) {
        bool res=true;
        vector<int> vals;
        dfs(root,vals);
        for(int i=1;i<vals.size();i++){
            if(vals[i-1]>=vals[i]){
                res=false;break;
            }
        }
        return res;
    }
    void dfs(TreeNode* root,vector<int> &vals){
        if(root==NULL) return;
        dfs(root->left,vals);
        vals.push_back(root->val);
        dfs(root->right,vals);
    }
};

 

 

中序遍历法改进:O(log(n)) 时间,O(1)空间;

/**
 * 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:
    TreeNode* pre;
    bool isValidBST(TreeNode* root) {
        pre=NULL;
        return dfs(root);
    }
    bool dfs(TreeNode* root){
        if(root==NULL) return true;
        if(!dfs(root->left)) return false;
        if(pre && pre->val>=root->val) return false;
        pre=root;
        if(!dfs(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:
    TreeNode* pre=NULL;
    bool isValidBST(TreeNode* root) {
        if(root==NULL) return true;
        if(!isValidBST(root->left)) return false;
        if(pre && pre->val>=root->val) return false;
        pre=root;
        if(!isValidBST(root->right)) return false;
        return true;
    }
};

 

posted @ 2019-04-05 00:33  Joel_Wang  阅读(115)  评论(0编辑  收藏  举报