【一次过】Lintcode 73. 前序遍历和中序遍历树构造二叉树

本文介绍如何使用前序遍历和中序遍历构造二叉树,并提供递归实现方式。通过对样例进行分析,展示如何定位根节点及划分左右子树,最后优化查找过程提高效率。

根据前序遍历和中序遍历树构造二叉树.

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

  2
 / \
1   3

注意事项

你可以假设树中不存在相同数值的节点


解题思路:

     1       
    / \   
   2   3   
  / \ / \   
 4  5 6  7

对于上图的树来说,
        index: 0 1 2 3 4 5 6
     先序遍历为: 1 2 4 5 3 6 7 
     中序遍历为: 4 2 5 1 6 3 7
为了清晰表示,我给节点上了颜色,红色是根节点,蓝色为左子树,绿色为右子树。
可以发现的规律是:
1. 先序遍历的从左数第一个为整棵树的根节点。
2. 中序遍历中根节点是左子树右子树的分割点。

再看这个树的左子树:
     先序遍历为: 2 4 5 
     中序遍历为: 4 2 5
依然可以套用上面发现的规律。

右子树:
     先序遍历为: 3 6 7 
     中序遍历为: 6 3 7
也是可以套用上面的规律的。

所以这道题可以用递归的方法解决。
具体解决方法是:
通过先序遍历找到第一个点作为根节点,在中序遍历中找到根节点并记录index。
因为中序遍历中根节点左边为左子树,所以可以记录左子树的长度并在先序遍历中依据这个长度找到左子树的区间,用同样方法可以找到右子树的区间。
递归的建立好左子树和右子树就好。

图解

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param inorder: A list of integers that inorder traversal of a tree
     * @param postorder: A list of integers that postorder traversal of a tree
     * @return: Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }
    
    public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd){
        if(inStart>inEnd || preStart>preEnd)
            return null;
            
        int rootVal = preorder[preStart];//先序遍历找到第一个点作为根节点
        int rootIndex = 0; //在中序遍历中找到根节点并记录index
        for(int i=inStart ; i<=inEnd ; i++){
            if(inorder[i] == rootVal){
                rootIndex = i;
                break;
            }
        }
        
        int len = rootIndex - inStart; //左子树的长度
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(preorder,preStart+1,preStart+len,inorder,inStart,rootIndex-1);
        root.right = buildTree(preorder,preStart+len+1,preEnd,inorder,rootIndex+1,inEnd);
        
        return root;
    }
}

优化:由于每次递归都需要在中序遍历数组中寻找根节点的位置索引,想到如果用hashmap集合存放inorder数组,查找效率更高

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param inorder: A list of integers that inorder traversal of a tree
     * @param postorder: A list of integers that postorder traversal of a tree
     * @return: Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        Map<Integer,Integer> map= new HashMap<>();//key为inorder数组中的值,value为对应的数组索引
        for(int i=0 ; i<inorder.length ; i++)
            map.put(inorder[i],i);
        
        return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1, map);
    }
    
    public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer,Integer> map){
        if(inStart>inEnd || preStart>preEnd)
            return null;
            
        int rootVal = preorder[preStart];//先序遍历找到第一个点作为根节点
        int rootIndex = map.get(rootVal); //在中序遍历中找到根节点并记录index
        
        int len = rootIndex - inStart; //左子树的长度
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(preorder,preStart+1,preStart+len,inorder,inStart,rootIndex-1,map);
        root.right = buildTree(preorder,preStart+len+1,preEnd,inorder,rootIndex+1,inEnd,map);
        
        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 ``` 注意这里简化了实际操作中的细节以便更清晰地表达核心概念。实际上应该考虑边界条件等问题以确保程序健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值