zoukankan      html  css  js  c++  java
  • 【LeetCode】验证二叉搜索树

    【问题】给定一个二叉树,判断其是否是一个有效的二叉搜索树。

    假设一个二叉搜索树具有如下特征:
    节点的左子树只包含小于当前节点的数。
    节点的右子树只包含大于当前节点的数。
    所有左子树和右子树自身必须也是二叉搜索树。

    示例 1:
    输入:
    2
    / 
    1 3
    输出: true
    示例 2:
    输入:
    5
    / 
    1 4
    / 
    3 6
    输出: false
    解释: 输入为: [5,1,4,null,null,3,6]。
    根节点的值为 5 ,但是其右子节点值为 4

    【思路】如何判断一棵二叉树是否为BST,很简单的思路就是:对这棵二叉树进行中序遍历,然后判断其中序遍历后的序列是不是单调递增的序列,如果是,则为一棵BST,否则不是。

    但是二叉树的中序遍历有两个版本,递归版和非递归版本,我们先来看递归版本,其实际就是一个dfs算法,从根节点依次向下深入,在递归体内我们需要设置两个变量min, max来进行数值边界的判断,以使得遍历后的序列为一个单调增序列!

    /**
     * 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 dfs(TreeNode* root, long int mi, long int ma){
            if(root == nullptr){
                return true;
            }
            if(root->val <= mi || root->val >= ma) return false;
            else return dfs(root->left, mi, root->val) && dfs(root->right, root->val, ma);
    
        }
    
        bool isValidBST(TreeNode* root) {
            if(root == NULL) return true;
            return dfs(root, INT64_MIN, INT64_MAX);
        }
    };

    我们还可以使用一个堆栈来实现二叉树的费递归版的中序遍历!!!

    /**
     * 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) {
            if(root == nullptr) return true;
            TreeNode* pre = nullptr;
            TreeNode* cur = root;
            stack<TreeNode*> sta;
            while(!sta.empty() || cur != nullptr){
                if(cur != nullptr){
                    sta.push(cur);
                    cur = cur->left;
                }else{
                    cur = sta.top();
                    sta.pop();
                    if(pre && cur->val <= pre->val) return false;
                    pre = cur;
                    cur = cur->right;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    编译原理-第二章 一个简单的语法指导编译器-2.4 语法制导翻译
    编译原理-第二章 一个简单的语法指导编译器-2.3 语法定义
    编译原理-第二章 一个简单的语法指导编译器-2.2 词法分析
    LeetCode 1347. Minimum Number of Steps to Make Two Strings Anagram
    LeetCode 1348. Tweet Counts Per Frequency
    1349. Maximum Students Taking Exam(DP,状态压缩)
    LeetCode 1345. Jump Game IV(BFS)
    LeetCode 212. Word Search II
    LeetCode 188. Best Time to Buy and Sell Stock IV (动态规划)
    LeetCode 187. Repeated DNA Sequences(位运算,hash)
  • 原文地址:https://www.cnblogs.com/zhudingtop/p/11530612.html
Copyright © 2011-2022 走看看