《剑指offer》4.重建二叉树

题目地址:https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解题思路:假设树的先序遍历是12453687,中序遍历是42516837。这里最重要的一点就是先序遍历可以提供根的所在,而根据中序遍历的性质知道根的所在就可以将序列分为左右子树。比如上述例子,我们知道1是根,所以根据中序遍历的结果425是左子树,而6837就是右子树。接下来根据切出来的左右子树的长度又可以在先序便利中确定左右子树对应的子序列(先序遍历也是先左子树后右子树)。根据这个流程,左子树的先序遍历和中序遍历分别是245和425,右子树的先序遍历和中序遍历则是3687和6837,我们重复以上方法,可以继续找到根和左右子树,直到剩下一个元素。可以看出这是一个比较明显的递归过程,对于寻找根所对应的下标,我们可以先建立一个HashMap,以免后面需要进行线行搜索,这样每次递归中就只需要常量操作就可以完成对根的确定和左右子树的分割。
算法最终相当于一次树的遍历,每个结点只会被访问一次,所以时间复杂度是O(n)。而空间我们需要建立一个map来存储元素到下标的映射,所以是O(n)。
 

import java.util.*;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre==null || in==null)
            return null;
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<in.length;i++)
            map.put(in[i],i);
        return helper(pre,0,pre.length-1,in,0,in.length-1,map);
    }
    public TreeNode helper(int[] pre,int preL,int preR,int[] in,int inL,int inR,HashMap<Integer,Integer> map){
        if(preL>preR||inL>inR){
            return null;
        }
        TreeNode root = new TreeNode(pre[preL]);
        int index = map.get(root.val);
        root.left = helper(pre,preL+1,index-inL+preL,in,inL,index-1,map);
        root.right = helper(pre,index-inL+preL+1,preR,in,index+1,inR,map);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28900249/article/details/89277398