【刷题】python 根据前序和中序重建二叉树(leetcode)

步骤:

1.在前序序列中找到根节点

2.在中序序列中,根据根节点的位置,区分左右子树集合

3.分别列出左右子树的前序序列和中序序列

4.回溯前序序列,重复上述步骤,直到将所有节点集合拆解为叶子节点

举例:

前序(根-左-右):1 2 4 7 3 5 6 8

中序(左-根-右):4 7 2 1 5 3 8 6

1.前序第一个数字是整个二叉树的根节点 ,根节点:1

2.中序序列,以根节点1区分左右子树集合,左子树集合:4 7 2,右子树集合:5 3 8 6 

3.左子树的前序序列:2 4 7,中序序列:4 7 2。右子树的前序序列:3 5 6 8 ,中序序列: 5 3 8 6

4.根据拆分的前序序列和中序序列,继续确定根节点,继续拆分

代码:

定义二叉树的类

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

递归重建二叉树

class Solution:
    def reConstructBinaryTree(self, pre, tin):#pre、tin分别是前序序列和中序序列
        if len(pre)>0:
            root = TreeNode(pre[0]) #前序序列的第一个肯定是当前子树的根节点
            rootidx = tin.index(root.val) #返回根节点在中序序列中的位置
            root.left = self.reConstructBinaryTree(pre[1:1+rootidx],tin[:rootidx])#重建左子树
            root.right = self.reConstructBinaryTree(pre[1+rootidx:],tin[rootidx+1:])#重建右子树
            return root

可以采用层序输出的方式验证生成的二叉树是否正确,用先进先出的队列依次保存层序遍历到的节点(该方法在类Solution下),然后遍历每个节点的左子节点和右子节点,代码实现如下:

    def PrintFromTopToBottom(self, root):
        ans=[]
        if root==None:
            return ans
        else:
            q=[root]
            while q:
                node=q.pop(0)
                ans.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            return ans

 完整代码:

class TreeNode:
    def __init__(self,x):
        self.val = x
        self.left = None
        self.right = None
        
class Solution:
    def reConstructBinaryTree(self, pre, tin):#pre、tin分别是前序序列和中序序列
        if len(pre)>0:
            root = TreeNode(pre[0])
            rootidx = tin.index(root.val)
            root.left = self.reConstructBinaryTree(pre[1:1+rootidx],tin[:rootidx])
            root.right = self.reConstructBinaryTree(pre[1+rootidx:],tin[rootidx+1:])
            return root
    
    def PrintFromTopToBottom(self, root):
        ans=[]
        if root==None:
            return ans
        else:
            q=[root]
            while q:
                node=q.pop(0)
                ans.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            return ans
        
pre = [1, 2, 4, 7, 3, 5, 6, 8]
tin = [4, 7, 2, 1, 5, 3, 8, 6]
a = Solution()
root = a.reConstructBinaryTree(pre,tin)
ans = a.PrintFromTopToBottom(root)
print(ans)

输出: [1, 2, 3, 4, 5, 6, 7, 8] 

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值