力扣230题(二叉搜索树、递归)
时间:2021-01-27 14:07:00
收藏:0
阅读:0
230.BST中第k小的元素
基本思想:
BST的中序遍历是升序序列。下标为k-1的元素就是第k个元素。
具体实现:
中序遍历后,找下标为k-1的元素。
代码:
class Solution: def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ def inorder(r): return inorder(r.left) + [r.val] + inorder(r.right) if r else [] return inorder(root)[k - 1]
538.把BST转换为累加树
基本思想:
每个节点的值修改为原来的节点值加上所有大于它的节点值之和。反序中序遍历,
具体实现:
nonlocal声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量。
代码:
class Solution: def convertBST(self, root: TreeNode) -> TreeNode: def dfs(root: TreeNode): nonlocal total if root: dfs(root.right) total += root.val root.val = total dfs(root.left) total = 0 dfs(root) return root
评论(0)