如何根据二叉树的前序遍历结果与中序遍历结果还原二叉树

public class Solution {
    int index=0;
    private TreeNode reConstructBinaryTree(int [] pre,int [] in,int left,int right){
        if(index>=pre.length||left>=right){
            return null;
        }
        int rootIndex=left;
        while(rootIndex<right){
            if(pre[index]==in[rootIndex]){
                break;
            }
            rootIndex++;
        }
        TreeNode newRoot=new TreeNode(in[rootIndex]);
        index++;
        newRoot.left=reConstructBinaryTree(pre,in,left,rootIndex);
        newRoot.right=reConstructBinaryTree(pre,in,rootIndex+1,right);
        return newRoot;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return reConstructBinaryTree(pre,in,0,in.length);
    }
}

在这里插入图片描述

### 重建二叉树的方法 通过前序遍历序遍历结果可以唯一确定一棵二叉树。这是因为前序遍历的第一个元素总是当前子树的根节点,在中序遍历列中找到这个根节点的位置,就可以区分出左子树右子树的部分。 #### 基本原理 在前序遍历列表中的首个元素表示整棵树的根节点[^1]。对于中序遍历而言,该根节点左侧的所有元素构成了其对应的左子树;右侧则对应着右子树[^2]。这一特性使得能够递归地解析并恢复原始结构。 #### 实现过程 为了实现上述逻辑,下面给出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_index_in_inorder = inorder.index(root_val) node = TreeNode(val=root_val) node.left = buildTree(preorder[:root_index_in_inorder], inorder[:root_index_in_inorder]) node.right = buildTree(preorder[root_index_in_inorder:], inorder[root_index_in_inorder + 1:]) return node ``` 这段程定义了一个`TreeNode`类用于创建新的节点实例,并实现了函数`buildTree()`来接收两个参数——分别是前序遍历(`preorder`)序遍历(`inorder`)得到的数值列表。此方法会不断移除前序遍历列表里的首项作为新建立节点的价值,同时依据这些值分割中序遍历列表成左右两部分继续构建子树直到完成整个重构工作。 #### 图解说明 假设存在如下输入数据: - `preorder`: `[3,9,20,15,7]` - `inorder`: `[9,3,15,20,7]` 按照以上描述的过程执行后可得下图所示结果(省略具体图形展示),其中每个圆圈代表一个节点及其存储的数据值,箭头指向表明父子关系方向。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值