python重构二叉树

前序+中序,中序+后序均可以构造出原本的树结构;前序加后序无法构造唯一的树结构。

假设节点是这样的:

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

假设树是这样的:

root=TreeNode(1)
root_1_1=TreeNode(2)
root_1_2=TreeNode(3)
root_1_1_1=TreeNode(4)
root_1_1_2=TreeNode(5)
root_1_2_1=TreeNode(6)
root.left=root_1_1
root.right=root_1_2
root_1_1.left=root_1_1_1
root_1_1.right=root_1_1_2
root_1_2.left=root_1_2_1

那么,现在写出前序和中序表达,使用以下函数,能得出正确的树结构;之后用后序的方式打印:

pre=[1,2,4,5,3,6]
post=[4,2,5,1,6,3]
root_pre_tin = s.reConstructBinaryTree_pre_tin(pre,post)
my_print_post(root_pre_tin)

桶同理,现在写出中序和后序表达,使用以下函数,能得出正确的树结构;之后用前序的方式打印:

tin=[4,2,5,1,6,3]
post=[4,5,2,6,3,1]
root_tin_post = s.reConstructBinaryTree_tin_post(tin,post,0,len(tin)-1,0,len(post)-1)
my_print_pre(root_tin_post)

sollution类定义如下:

class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree_pre_tin(self, pre, tin):
        # write code here
        if not pre or not tin:
            return None
        else:
            root=TreeNode(pre.pop(0))
            index=tin.index(root.val)
            # print("root",root.val)
            # print("left",pre,tin[0:index])
            # print("right",pre,tin[1+index:])
            root.left=self.reConstructBinaryTree_pre_tin(pre,tin[0:index])
            root.right=self.reConstructBinaryTree_pre_tin(pre,tin[index+1:])
        return root

    def reConstructBinaryTree_tin_post(self, tin,post,tin_s,tin_end,post_s,post_e):
        # write code here
        root = TreeNode(post[post_e])
        if post_s==post_e:
            return root
        index=tin.index(root.val)
        if index-1>=tin_s:
            root.left=self.reConstructBinaryTree_tin_post(tin,post,tin_s,index-1,post_s,post_s+index-1-tin_s)
        if index+1<=tin_end:
            root.right=self.reConstructBinaryTree_tin_post(tin,post,index+1,tin_end,post_s+index-tin_s,post_e-1)
        return root

自定义打印方式如下:

def my_print_pre(root):

    if root:
        print("当前节点:",root.val)
    if root.left:
        print(root.val,"的左节点")
        my_print_pre(root.left)
    if root.right:
        print(root.val,"的右节点")
        my_print_pre(root.right)

def my_print_post(root):

    if root.left:
        my_print_post(root.left)
    if root.right:
        my_print_post(root.right)
    if root:
        print(root.val)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值