LintCode 72-中序遍历和后序遍历树构造二叉树

本文介绍了一种通过中序遍历和后序遍历构建二叉树的方法。具体实现包括两个主要函数:`buildTree` 和 `InandpostTree`。通过递归方式构造树结构,该方法适用于计算机科学中的数据结构学习。

仿照《王道数据结构2016版》 127页第6题。

   static public TreeNode buildTree(int[] inorder, int[] postorder) {
        // write your code here
        if(inorder.length==0) return null;
        return InandpostTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);

    }

static public TreeNode InandpostTree(int []inorder,int []postorder,int s1,int e1,int s2,int e2)
{
    TreeNode root=new TreeNode(postorder[e2]);

    int i=s1;

    for(;inorder[i]!=root.val;i++);

    int llen=i-s1;
    int rlen=e1-i;

    if(llen>0){
        root.left =InandpostTree(inorder,postorder,s1,s1+llen-1,s2,s2+llen-1);

    }
    if(rlen>0){
        root.right=InandpostTree(inorder,postorder,e1-rlen+1,e1,e2-rlen,e2-1);


    }

    return root;
}
}
### 中序遍历后序遍历构造二叉树的方法 要通过中序遍历后序遍历的结果重建二叉树,可以采用递归方法。以下是详细的说明: #### 思路分析 1. 后序遍历的最后一个节点总是当前子树的根节点[^1]。 2. 利用该根节点,在中序遍历序列中找到其位置,从而划分出左子树右子树的范围[^3]。 3. 对于左子树右子树分别重复上述过程,直至处理完所有的节点。 #### 实现步骤 下面是一个基于 Java 的实现代码示例,用于根据中序遍历后序遍历结果构建二叉树: ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class BuildTreeFromInPost { private int postIndex; public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder == null || postorder == null || inorder.length != postorder.length) { return null; } this.postIndex = postorder.length - 1; // 初始化为后序遍历的最后一个索引 return helper(inorder, postorder, 0, inorder.length - 1); } private TreeNode helper(int[] inorder, int[] postorder, int inStart, int inEnd) { if (inStart > inEnd) { return null; } // 当前子树的根节点是从后序遍历中的postIndex获取到的 TreeNode root = new TreeNode(postorder[postIndex]); postIndex--; // 更新后序遍历指针 // 在中序遍历中查找根节点的位置 int inIndex = findIndex(inorder, inStart, inEnd, root.val); // 构建右子树(注意这里是先构建右子树) root.right = helper(inorder, postorder, inIndex + 1, inEnd); // 构建左子树 root.left = helper(inorder, postorder, inStart, inIndex - 1); return root; } private int findIndex(int[] inorder, int start, int end, int value) { for (int i = start; i <= end; i++) { if (inorder[i] == value) { return i; } } return -1; } } ``` #### 关键点解释 1. **后序遍历的特点**:后序遍历的顺序是“左 -> 右 -> 根”,因此每次递归时可以从 `postorder` 数组的末尾取出当前子树的根节点[^4]。 2. **中序遍历的作用**:利用中序遍历能够快速定位左右子树的边界,进而缩小问题规模[^3]。 3. **递归终止条件**:当 `inStart > inEnd` 时表示当前区间为空,返回 `null` 即可[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值