剑指 offer(python)

求二叉搜索树的第K大的节点

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def inorder( root, ans=[]):
    if root.left:
        inorder(root.left, ans)
    ans.append(root.val)
    if root.right:
        inorder(root.right, ans)
    return ans

h1 = TreeNode(5)
h2 = TreeNode(3)
h3 = TreeNode(7)
h4 = TreeNode(2)
h5 = TreeNode(4)

h1.left = h2
h1.right = h3
h2.left = h4
h2.right = h5

res = inorder(h1)
print(res)
发布了77 篇原创文章 · 获赞 9 · 访问量 6742

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/101120594