python-6. 重建二叉树

题目描述:

  • 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树,假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如,输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8, 6},则重建如下图所示的二叉树并输出它的头结点。二叉树节点的定义如下:
struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
}

解题思路:

  • 根据二叉树的前序遍历可和中序遍历可以确定根节点的值、左子树节点的值和右子树节点的值。
    • 首先在前序中确定根节点,然后再中序中找到对应的根节点位置,左边为左子树、右边为右子树,完成划分
  • 以上述同样的方法递归构建左子树、右子树即可。
class BinaryTreeNode:
    def __init__(self, val):
        self.val = val
        self.LeftNode = None
        self.RightNode = None
class Solution:
    def __init__(self, list_pre, list_in):
        self.list_pre = list_pre
        self.list_in = list_in
    def ReconstructTree(self):
        if self.list_pre is None or self.list_in is None:
            return None
        return self.ConstructCore(0, len(self.list_pre) - 1, 0, len(self.list_in) - 1)
    def ConstructCore(self, startPreoder, endPreorder, startInorder, endInorder):
        rootValue = self.list_pre[startPreoder]
        root = BinaryTreeNode(rootValue)
        root.LeftNode = root.RightNode = None
        # 递归终止条件
        if startPreoder == endPreorder:
            if startPreoder == endPreorder and self.list_pre[startPreoder] == self.list_in[startInorder]:
                return root
            else: raise ValueError('invalid input')
        # 在中序序列中找到根节点位置
        rootInorder = startInorder
        while rootInorder <= endInorder and self.list_in[rootInorder] != rootValue:
            rootInorder += 1
        if rootInorder == endInorder and self.list_in[rootInorder] != rootValue:
            raise ValueError('invalid input')
        # 划分左右子树
        leftLength = rootInorder - startInorder
        leftPreorderEnd = startPreoder + leftLength
        # 构建左子树
        if leftLength > 0:
            root.LeftNode = self.ConstructCore(startPreoder + 1, leftPreorderEnd, startInorder, rootInorder - 1)
        # 构建右子树
        if leftLength < endPreorder - startPreoder:
            root.RightNode = self.ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder)
        return root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值