# leetcode-105 从前序与中序遍历序列构造二叉树（Medium）

## 题目描述

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

3
/ \
9  20
/  \
15   7


## 给定代码

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {

}
}


## 题解一

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int [] pre;
private int [] in;
private HashMap<Integer, Integer> map = new HashMap<>();

public TreeNode buildTree(int[] preorder, int[] inorder) {
for (int i = 0 ; i < inorder.length ; i++) {
map.put(inorder[i], i);
}
pre = preorder;
in = inorder;
return deep(0, preorder.length - 1, 0, preorder.length - 1);
}

private TreeNode deep(int start, int end, int start2, int end2)
{
if (start > end || start2 > end2) {
return null;
} else {
TreeNode result = new TreeNode(pre[start]);
int index = map.get(pre[start]);
int leftLength = index - start2;
int rightLength = end2 - index;
if (leftLength > 0)
result.left = deep(start + 1, start + 1 + leftLength, start2, index - 1);
if (rightLength > 0)
result.right = deep(start + leftLength + 1, end, index + 1, end2);

return result;
}
}
}


03-09 79

03-05 42

05-22 54

12-19 253

05-22 59

05-28 3039

08-05 152

02-26 45

07-14 114

09-23 335

04-10 203

11-28 57

11-06 34

07-24 3011

11-17 114

05-22 34

08-13 117

11-16 70

06-25 209

05-08 68

04-14 60万+

03-13 15万+

02-19 18万+

03-01 13万+

03-04 14万+

03-06 3739

03-08 7万+

04-25 7万+

03-10 13万+

03-10 19万+

03-12 11万+

03-13 11万+

03-16 2884

03-18 1万+

03-19 8万+

03-19 4万+

03-20 1万+

03-22 5万+

03-24 3万+

03-25 3万+

05-08 5万+

03-25 9万+

03-30 4万+

03-26 3027

03-29 22万+

04-10 1960

03-29 10万+

03-30 17万+

04-17 5万+

04-01 3427

03-23 1万+

04-02 1万+

04-02 4万+

06-01 877

04-06 7万+

04-06 5034

04-09 8万+

04-09 3万+

05-17 9820

04-11 4万+

04-15 6万+

04-18 5万+

04-20 5万+

05-03 1万+

05-16 6万+

05-06 2万+

05-07 1万+

05-08 4万+

05-12 1万+

05-14 7517

05-16 2484

05-16 1万+

05-16 2万+

05-30 2791

05-18 9329

05-18 6042

05-18 4385

05-21 9010

05-21 9174

#### 老码农吐血建议：2020年，低于1w的程序员要注意了...

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客