题目四:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
class TreeNode:
def __init__(self,x):
self.val=x
self.left=None
self.right=None
class Solution:
def reConstuctBinaryTree(self,pre,tin):
if len(pre)==0:
return None
root_data=TreeNode(pre[0])
i=tin.index(pre[0])
root_data.left=self.reConstuctBinaryTree(pre[1:1+i],tin[:i])
root_data.right=self.reConstuctBinaryTree(pre[1+i:],tin[i+1:])
return root_data
def printFromTopToBottom(self,root):
if not root:
return []
result=[]
queue=[]
queue.append(root)
while len(queue)>0:
t=queue.pop(0)
# 必须加0,pop()默认为从尾输出
result.append(t.val)
if t.left:
queue.append(t.left)
if t.right:
queue.append(t.right)
return result
so=Solution()
pre=[1,2,4,7,3,5,6,8]
tin=[4,7,2,1,5,3,8,6]
rd=so.reConstuctBinaryTree(pre,tin)
print(type(rd))
print(rd)
print(rd.val)
print(rd.left.val)
print(rd.right.val)
print(rd.left.left.val)
print(rd.right.right.val)
result=so.printFromTopToBottom(rd)
print(result)
<class '__main__.TreeNode'>
<__main__.TreeNode object at 0x00000253334BCAC8>
1
2
3
4
6
[1, 2, 3, 4, 5, 6, 7, 8]
参考:https://blog.csdn.net/weixin_38339143/article/details/79897670
参考:https://github.com/leeguandong/Interview-code-practice-python/blob/master/剑指offer/从上往下打印二叉树.py
本题主要采用递归的思想。首先介绍一下根据前序遍历和中序遍历来构建二叉树的思路:前序遍历的第一个则是二叉树的根,找到根在中序遍历中的位置,则根将中序遍历分为了两部分,根的左边为二叉树的左子树,根的右边为二叉树的右子树,对应左右子树在可前序遍历中是连续存在的,根据该思路可以继续分别寻找左子树与右子树的根节点,递归进行。首先判断二叉树是否为空,进行长度的判断即可。还要注意将根定义成节点的形式。在进行本函数的递归调用时,需要在本函数名前面加上self
作者:太阳旁边的星星
来源:CSDN
原文:https://blog.csdn.net/weixin_38339143/article/details/79897670
版权声明:本文为博主原创文章,转载请附上博文链接!