当前位置:网站首页>二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
2022-06-29 23:03:00 【Steven迪文】
二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
230. 二叉搜索树中第K小的元素
解题思路:
- 二叉搜索树的中序遍历,是节点的升序顺序,这也是二叉搜索树的特性。
- 设置一个值,来记录遍历的层数是否为 K。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
self.count = 0
self.res = 0
self.traverse(root,k)
return self.res
def traverse(self, root, k):
if not root:
return
self.traverse(root.left,k)
self.count += 1
if k == self.count:
self.res = root.val
return
self.traverse(root.right,k)
1038. 从二叉搜索树到更大和树
解题思路:
- 还是利用二叉搜索树中序遍历的特性, 但中序遍历是先遍历左子树,我们没办法算出大于等于当前节点的累加和。
- 所以颠倒一下左右子树的先后遍历顺序。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
self.res = 0
self.traverse(root)
return root
def traverse(self, root):
if not root:
return None
self.traverse(root.right) # 先遍历右子树
self.res += root.val
root.val = self.res
self.traverse(root.left)
边栏推荐
- uniapp复制内容到剪贴板
- Go zero micro Service Practice Series (VII. How to optimize such a high demand)
- Does Australia require that PVC plastic sheets comply with as/nzs 1530.3 with a flame spread index of 0?
- 動態代理的實現原理
- 缓冲流练习
- 架构实战营模块 5 作业
- Solution to version conflict of flutter plug-in
- Incluxdb time series database system
- Design of Distributed Message Oriented Middleware
- Constexpr function
猜你喜欢
C pointer advanced 2-- > function pointer array callback function simplifies calculator code, and implements qsort function based on callback function simulation
Talk about auto in MySQL in detail_ What is the function of increment
为什么 JSX 语法这么香?
How can the local / park do a good job in industrial analysis?
nrm详解
Gnawing down the big bone - sorting (I)
众昂矿业:萤石助力氟产业锂电建设发展
Project 1 - buffer pool [cmu 15-445645] notes
Status acquisition and control system of on-site express cabinet
Speech signal processing (II): phonation physiology, auditory physiology and auditory psychology
随机推荐
“微博评论”的高性能高可用计算架构
远程沟通高效的自我总结| 社区征文
Dépannage de l'étiquette: impossible d'ouvrir l'image marquée
成为唯一的key
R & D test time ratio, bug data analysis
Implementation principle of dynamic agent
按头安利 好看又实用的点胶机 SolidWorks模型素材看这里
redis客户端
MetaQ集群安装测试
Does Australia require that PVC plastic sheets comply with as/nzs 1530.3 with a flame spread index of 0?
触摸按键与按键控制对应的LED状态翻转
论文阅读《Large-Scale Direct SLAM with Stereo Cameras》
The server quickly sets up the alist integrated network disk website [pagoda panel one click deployment of alist]
Under the epidemic, I left my job for a year, and my income increased 10 times
字节云数据库未来方向的探索与实践
微博系统中”微博评论“的高性能高可用计算架构
分布式消息中间件设计
constexpr 函数
Leetcode 1385. Distance value between two arrays
label问题排查:打不开标注好的图像