leetcode hot100 二叉搜索树

二叉搜索树的第k小的数

python 复制代码
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        # 二叉搜索树的中序遍历是 升序排列的, 求第k小的,即第k个数
        self.res = []
        def fun(root):
            if not root:
                return
            
            fun(root.left)
            if root:
                self.res.append(root.val)
            fun(root.right)
            return 
        fun(root)
        return self.res[k-1]

验证二叉搜索树

python 复制代码
class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        self.res = []
        self.flag = True
        def func(root):
            if not root:
                return
            func(root.left)
            if root:
                self.res.append(root.val)
                if len(self.res)>1 and self.res[-1] <= self.res[-2]:
                    self.flag = False
                    return 
            func(root.right)

            return 

        func(root)
        return self.flag
相关推荐
CoovallyAIHub几秒前
全球首个精细梯田地块数据集GTPBD发布:为梯田遥感研究填补空白(附数据地址)
深度学习·算法·计算机视觉
CoovallyAIHub25 分钟前
【一周AI风暴】周鸿祎放话“不用AI就裁员”,前谷歌CEO鼓吹对华996血拼!
深度学习·算法·计算机视觉
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 55: 子集、找出所有子集的异或总和再求和
数据结构·算法·leetcode·决策树·深度优先·剪枝
熬了夜的程序员1 小时前
【LeetCode】48. 旋转图像
算法·leetcode·链表·职场和发展·深度优先
Q741_1471 小时前
C++ 位运算 高频面试考点 力扣 268. 丢失的数字 题解 每日一题
c++·算法·leetcode·面试·位运算
未知陨落1 小时前
LeetCode:79.跳跃游戏Ⅱ
算法·leetcode
未知陨落1 小时前
LeetCode:74.数组中的第K个最大元素
算法·leetcode
电子_咸鱼1 小时前
LeetCode-hot100——验证二叉搜索树
开发语言·数据结构·c++·算法·leetcode·深度优先
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 56: 全排列II、话号码的字母组合
数据结构·算法·leetcode·决策树·链表·职场和发展·深度优先
Imxyk2 小时前
Codeforces Round 1052 (Div. 2) C. Wrong Binary Searchong Binary Search
c语言·c++·算法