使用中序遍历,返回第k个数来处理
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def kthLargest(self, root: TreeNode, k: int) -> int: def helper(root): return helper(root.left) + [root.val] + helper(root.right) if root else [] return helper(root)[-k]
class Solution: def kthLargest(self, root: TreeNode, k: int) -> int: def dfs(root): if not root: return dfs(root.right) if self.k == 0: return self.k -= 1 if self.k == 0: self.res = root.val dfs(root.left) self.k = k dfs(root) return self.res
本文来自博客园,作者:topass123,转载请注明原文链接:https://www.cnblogs.com/topass123/p/12764829.html