【每日一题-leetcode】105.从前序与中序遍历序列构造二叉树

105.从前序与中序遍历序列构造二叉树

  1. 从前序与中序遍历序列构造二叉树

难度中等422

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

注意:

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

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

    3
   / 
  9  20
    /  
   15   7

递归

//1.前序遍历的顺序为 根左右。
//2.map存储中序遍历 key为值 value 为index
Map<Integer,Integer> result = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
    for(int i=0;i<inorder.length;i++){
        result.put(inorder[i],i);
    }
    return recur(preorder,0,preorder.length-1,0);
}

public TreeNode recur(int [] preorder,int preL,int preR,int inoL){
    if(preL>preR)  return null;
    TreeNode root = new TreeNode(preorder[preL]);
    int index = result.get(root.val);
    int indexSize = index - inoL;
    //重建左子树
    root.left = recur(preorder,preL+1,preL+indexSize,inoL);
    //重建右子树
    root.right = recur(preorder,preL+1+indexSize,preR,inoL+indexSize+1);
    return root;
}
原文地址:https://www.cnblogs.com/qxlxi/p/12860621.html