• 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;
        }
    };
  • 相关阅读:
    11、sqlite
    10、正则
    9、bs4
    8、异常与import
    7、文件
    6、函数
    4、字典及集合
    3、元组
    1、python基本语法
    shell编程 15 --- shell 脚本调试技巧
  • 原文地址:https://www.cnblogs.com/joelwang/p/10657715.html
Copyright © 2020-2023  润新知