第K大节点
dfs,中序遍历先便利右子树,再遍历左子树,如果中序遍历是升序的情况.
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
第k小节点(牛客)
dfs,中序遍历先便利左子树,再遍历右子树,如果中序遍历是升序的情况.
class Solution:
def KthNode(self, pRoot, k):
self.k = k
self.res = None
def dfs(root):
if not root:
return
dfs(root.left)
if self.k == 0:
return
self.k -=1
if self.k == 0:
self.res = root
return
dfs(root.right)
dfs(pRoot)
return self.res