zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    Spring MVC 入门示例讲解
    使用Word2013,发布博文到博客园
    走过2103,迈向2014
    C#中的字符串拼接@,$
    ORA-22922:nonexistent LOB value问题及listagg()函数
    证明一个数是不是存在于该数组中
    论java中System.arrayCopy()与Arrays.copyOf()的区别
    JSP中获取各种路径的方法
    JavaScript中变量声明有var和没var的区别
    JavaScript:理解事件循环
  • 原文地址:https://www.cnblogs.com/joelwang/p/10657715.html
Copyright © 2011-2022 走看看