二叉搜索数第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:
        # 中序遍历后倒数第k个
        if not root: return
        stack = []
        cur = root
        results = []
        while stack or cur:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            results.append(cur.val)
            cur = cur.right
        if k > len(results): return 

        return results[len(results)-k]       
            

                      
        # 中序遍历递归版本
        results = []
        def inorder(root):
            if not root: return None
            inorder(root.left)
            results.append(root.val)
            inorder(root.right)
        inorder(root)
        if k > len(results): return
        return results[len(results)-k]
posted @ 2021-03-07 23:18  KbMan  阅读(35)  评论(0编辑  收藏  举报