剑指offer54.二叉搜索树的第k大节点

思路:按照中序遍历的顺序遍历一棵二叉树,则遍历序列的数值是递增排序的。用中序遍历后就很容易找到第 k 大节点

class Solution(object):#这种解法试求第 k 小节点
    def kthNode(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: TreeNode
        """
        node = root
        stack = []
        stack.append(node)
        num = 0
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            num +=1#把 print 改成计数就好了
            if num == k:
                return node
            node = node.right

你可能感兴趣的:(剑指offer54.二叉搜索树的第k大节点)