根据一棵树的中序遍历与后序遍历构造二叉树(递归思路)

根据一棵树的中序遍历与后序遍历构造二叉树

题目

注意:
你可以假设树中没有重复的元素。

例如,给出:
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:
在这里插入图片描述

思路分析

二叉树相关的很多问题的解决思路都有分治法的思想在里面。
复习一下分治法的思想:把原问题分解(Divide)成若干个与原问题结构相同但规模更小的子问题,待子问题解决(Conquer)以后,再合并(Combine)它们,原问题就得以解决。
在这里插入图片描述
用一个普遍的例子进行具体理解:
在这里插入图片描述

参考代码

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class Solution {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int inLen = inorder.length;
        int postLen = postorder.length;
        
        if (inLen != postLen) {
            throw new RuntimeException("输入错误");
        }
        return buildTree(inorder, 0, inLen - 1, postorder, 0, postLen - 1);
    }
    
    /**
     * 使用中序遍历序列 inorder 的子区间 [inLeft, inRight]
     * 与后序遍历序列 postorder 的子区间 [postLeft, postRight] 构建二叉树
     *
     * @param inorder   中序遍历序列
     * @param inLeft    中序遍历序列的左边界
     * @param inRight   中序遍历序列的右边界
     * @param postorder 后序遍历序列
     * @param postLeft  后序遍历序列的左边界
     * @param postRight 后序遍历序列的右边界
     * @return 二叉树的根结点
     */
     
    private TreeNode buildTree(int[] inorder, int inLeft, int inRight,
                               int[] postorder, int postLeft, int postRight) {
        if (inLeft > inRight || postLeft > postRight) {
            return null;
        }

        int pivot = postorder[postRight];
        int pivotIndex = inLeft;

        while (inorder[pivotIndex] != pivot) {
            pivotIndex++;
        }
        TreeNode root = new TreeNode(pivot);
        root.left = buildTree(inorder, inLeft, pivotIndex - 1,
                postorder, postLeft, postRight - inRight + pivotIndex - 1);

        root.right = buildTree(inorder, pivotIndex + 1, inRight,
                postorder, postRight - inRight + pivotIndex, postRight - 1);
        return root;
    }
}
### 使用前序遍历和中序遍历重建二叉树 在处理二叉树的重构问题时,利用前序遍历和中序遍历可以有效地恢复原始结构。前序遍历提供了一个访问节点的方式,即先访问根节点再依次访问左子树和右子树;而中序遍历则是按照左子树、根节点再到右子树这样的顺序进行访问。 #### 方法概述 为了从这两种遍历结果中重新创建二叉树,关键是理解前序遍历的第一个元素总是当前子树的根节点[^1]。一旦知道了根节点,则可以在中序遍历列表里定位到该根的位置,从而区分出哪些部分属于左子树以及哪些部分构成右子树[^3]。 具体来说: - **确定根节点**:从前序遍历序列取第一个值作为当前层次上的根节点。 - **分割左右子树**:依据此根节点,在中序遍历序列查找对应位置,以此为界线左侧的部分代表左子树的所有成员,右侧则表示右子树的内容。 - **递归构建子树**:针对分离出来的每一段新的前序中序组合再次执行相同的操作直到不能再分为止。 下面是一个具体的例子来展示这一过程是如何工作的[^4]。 假设给定的前序遍历(preorder)为 `[3, 9, 20, 15, 7]` ,对应的中序遍历(inorder)为 `[9, 3, 15, 20, 7]` 。根据上述方法可知: - `preorder[0]=3` 是整个树的根; - 查找 `3` 在 `inorder` 中的位置得知它的左边只有 `9` 属于左子树,右边有三个数 `[15, 20, 7]` 组成右子树; - 接下来继续分析各分支... 最终得到如下图所示的二叉树结构: ``` 3 / \ 9 20 / \ 15 7 ``` #### Python 实现代码 下面是基于以上逻辑编写的Python函数用于根据前序和中序遍历来重建二叉树: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder.pop(0) root = TreeNode(root_val) index_of_root_in_inorder = inorder.index(root_val) root.left = buildTree(preorder[:index_of_root_in_inorder], inorder[:index_of_root_in_inorder]) root.right = buildTree(preorder[index_of_root_in_inorder:], inorder[index_of_root_in_inorder + 1:]) return root ``` 注意这里简化了实际操作中的细节以便更清晰地表达核心概念。实际上应该考虑边界条件等问题以确保程序健壮性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值