jz054.二叉搜索树的第k大节点

 

题目链接

只要中序遍历一下二叉搜索树就容易找到,如算法1所示,当然也可以用k计数,一点点减1,直到0为止返回正确的数即可。这个算法的时间复杂度是O(N),空间复杂度是O(N),当树退化为链表时。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthLargest1(self, root: TreeNode, k: int) -> int: 
        self.ans = []
        def traversal(node):
            if not node:
                return
            if node.left:
                traversal(node.left)
            self.ans.append(node.val) 
            if node.right:
                traversal(node.right)
        traversal(root)
        return self.ans[-k]

    def kthLargest2(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