首页 > 其他分享 >LeetCode 98. 验证二叉搜索树

LeetCode 98. 验证二叉搜索树

时间:2023-05-24 14:44:06浏览次数:37  
标签:return val res dfs 二叉 98 root LeetCode

class Solution {
public:
    vector<int> dfs(TreeNode* root)//依次返回是否是二叉搜索树,最大值最小值
    {
        vector<int> res{1,root->val,root->val};
        if(root->left)
        {
            auto l=dfs(root->left);
            res[1]=max(res[1],l[1]);
            res[2]=min(res[2],l[2]);
            if(root->val<=l[1]||!l[0])  res[0]=0;
        }
        if(root->right)
        {
            auto r=dfs(root->right);
            res[1]=max(res[1],r[1]);
            res[2]=min(res[2],r[2]);
            if(root->val>=r[2]||!r[0])  res[0]=0;
        }
        return res;
    }
    bool isValidBST(TreeNode* root) {
        return dfs(root)[0];
    }
};

标签:return,val,res,dfs,二叉,98,root,LeetCode
From: https://www.cnblogs.com/tangxibomb/p/17428264.html

相关文章

  • LeetCode 222. 完全二叉树的节点个数
    classSolution{public:intcountNodes(TreeNode*root){if(!root)return0;autol=root->left,r=root->right;intx=1,y=1;//记录左右两边层数while(l)l=l->left,x++;while(r)r=r->right,y++;......
  • 二刷Leetcode-Days07
    动规:/***70.爬楼梯*@paramn*@return*/publicintclimbStairs(intn){if(n<=2){returnn;}int[]dp=newint[n];dp[0]=1;dp[1]=2;for(inti=2;i......
  • Acwing 798.差分矩阵(模板)
    题目#include<iostream>usingnamespacestd;constintN=1010;intn,m,q;inta[N][N],b[N][N];voidinsert(intx1,inty1,intx2,inty2,intc){b[x1][y1]+=c;b[x2+1][y1]-=c;b[x1][y2+1]-=c;b[x2+1][y2+1]+=......
  • 加分二叉树
    题目描述设一个\(n\)个节点的二叉树\(\text{tree}\)的中序遍历为\((1,2,3,\ldots,n)\),其中数字\(1,2,3,\ldots,n\)为节点编号。每个节点都有一个分数(均为正整数),记第\(i\)个节点的分数为\(d_i\),\(\text{tree}\)及它的每个子树都有一个加分,任一棵子树\(\text{subtree}\)......
  • LeetCode 62.不同路径
    1.题目:一个机器人位于一个mxn 网格的左上角(起始点在下图中标记为“Start”)。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。问总共有多少条不同的路径?示例1:输入:m=3,n=7输出:28来源:力扣(LeetCode)链接:https://leetcode.c......
  • CVE-2022-22980
    #CVE-2022-22980SpringDataMongoDBSpEL表达式注入importrequestsimporturllibimportbase64importargparsedefpoc(url,ip,prot):urll=f'{url}/?name='shell=f'/bin/bash-i>&/dev/tcp/{ip}/{prot}0>&1'shell=s......
  • leetcode2215哈希列表的应用
    哈希列表存储的是不重复的元素,使用两个哈希列表存储这两个数组。再遍历其中一个哈希列表,查看是否存在另一个哈希列表中set.insert()set1.count(元素)for(intnum:nums1){set1.insert(num);}for(intnum:set1){if(!set2.count(num)){res[0].push_back(num);......
  • poj-1988
    //564K 282MS C++#include<cstdio>#include<cstring>#include<iostream>usingnamespacestd;structUF_Node{ intup; intcount; intparent;};typedefstructUF_NodeUF_Node;UF_NodeUF_Array[30001];voidcreat(){ intc; for(......
  • 代码随想录算法训练营第十四天|144. 二叉树的前序遍历、145. 二叉树的后序遍历、94.
    【参考链接】1.满二叉树,完全二叉树,二叉搜索树(有数值,有序树)。2.平衡二叉搜索树:又被称为AVL(Adelson-VelskyandLandis)树,且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。3.优先级队列其实是一个堆,堆就是一棵完全二叉......
  • bst中序-leetcode230二叉搜索树第k个元素
    给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从1开始计数)。示例1:输入:root=[3,1,4,null,2],k=1输出:1示例2:输入:root=[5,3,6,2,4,null,null,1],k=3输出:3提示:树中的节点数为 n 。1<=k<=n<=1040<=Node.val<......