版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84954812
已知中序、后序构造二叉树
递归算法
def buildTree(inorder, postorder):
if inorder and postorder:
postRootVal = postorder.pop()
inRootIdx = inorder.index(postRootVal)
root = TreeNode(postRootVal)
""" 解释:
当从 postorder 中 pop 时,首先会命中 right child ,
所以,在构造树时,需要先设置 right ,再设置 left 。
"""
root.right = self.buildTree(inorder[inRootIdx+1:], postorder)
root.left = self.buildTree(inorder[:inRootIdx], postorder)
return root
参考文献
- 106. Construct Binary Tree from Inorder and Postorder - LeetCode;
- 这是印象笔记中的笔记,如果是在CSDN手机APP上查看此博客,请在印象笔记手机APP中搜索该参考文献:https://app.yinxiang.com/shard/s44/nl/9329661/e2a2758d-7c33-4fbd-99e0-74ff56457b82。