# 面试题07. 重建二叉树

3


/
9 20
/
15 7

0 <= 节点个数 <= 5000

/**

• Definition for a binary tree node.

• public class TreeNode {

• int val;

• TreeNode left;

• TreeNode right;

• TreeNode(int x) { val = x; }

• }
*/
class Solution {
private static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
public static void init(HashMap map,int [] inorder) {
for(int i = 0;i<inorder.length;i++) {
map.put(inorder[i], i);
}
}

public static TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length == 0) {
return null;
}
if(preorder.length == 1) {
return new TreeNode(preorder[0]);
}
init(map,inorder);
return myBuildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}

public static TreeNode myBuildTree(int[] preorder, int[] inorder,int pstart,int pend,int istart,int iend) {
if(istart > iend || pstart > pend) {
return null;
}
if(istart == iend || pstart == pend) {
return new TreeNode(preorder[pstart]);
}
//前序的首位的值
int num = preorder[pstart];
TreeNode root = new TreeNode(num);
//前序的首位在中序中的位置
int index = map.get(num);
int len = index-istart;
/左子树节点在前序遍历中的区间为[pstart+1,pstart+len],在中序遍历中的区间为[istart,index-1]/
root.left = myBuildTree(preorder, inorder, pstart+1, pstart+len, istart, index-1);
/右子树节点在前序遍历中的区间为[pstart+len+1,pend],在中序遍历中的区间为[index+1, iend]/
root.right = myBuildTree(preorder, inorder, pstart+len+1, pend, index+1, iend);
return root;
}
}

03-16 55

07-17 65

08-29 50

03-18 78

04-13 22

03-25 79

04-14 21

04-06 33

03-27 23

03-03 28

05-01 37

05-24 17

02-16 24

02-21 28

03-19 80万+

04-14 56万+

02-19 16万+

02-27 7万+

02-28 4万+

03-01 12万+

03-01 11万+

03-03 6223

03-04 12万+

03-05 9799

03-05 5万+

03-08 6万+

03-08 1万+

04-25 6万+

03-10 12万+

03-10 17万+

03-10 6407

03-12 10万+

03-13 10万+

03-16 1万+

03-19 7万+

03-20 5120

03-23 1万+

03-24 3万+

03-25 2万+

03-25 8万+

03-27 1万+

03-29 20万+

03-29 9万+

03-30 14万+

05-21 2967

03-31 1万+

05-25 5277

03-23 1万+

04-02 3万+

05-06 2万+

04-05 1万+

04-06 6万+

04-09 1万+

04-09 7万+

04-09 4758

04-10 4300

04-11 2万+

04-15 5万+

04-18 1万+

04-18 3820

04-18 4万+

04-20 3万+

04-24 2万+

04-26 3702

04-24 4215

04-30 7562

05-16 4万+

05-08 3万+

05-10 1947

05-11 3万+

05-13 6785

05-19 5718

05-13 9788

05-14 3696

05-14 6177

05-16 1972

05-16 1374

05-16 9384

05-16 1万+

#### boss说了：有谁要再用double定义商品金额，就自己收拾家伙走

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客