题目:
思路+代码:
思路一:
pythonic写法:三行代码,中序遍历二叉树返回遍历list
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
# pythonic写法
def dfs(root):
return dfs(root.left) + [root.val] + dfs(root.right) if root else []
return dfs(root)[-k]
思路二:
递归写法,逆中序遍历,遍历到第K大节点就停止;
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
# # 逆中序遍历,右中左顺序进行查找;设置两个类变量,self.k,和self.result
def dfs(root):
if not root:
return
dfs(root.right)
self.k -= 1 # 遍历完当前这个节点,k-1; 因为 1<=k<= 元素个数
if self.k == 0:
self.res = root.val # 对当前节点进行判断是否是第k个节点
return
dfs(root.left)
self.k = k
dfs(root)
return self.res