# 中序/前序+中序/后序构建二叉树

例如，给出

3
/ \
9  20
/  \
15   7

class Solution {
private Map<Integer, Integer> indexMap;

public TreeNode myBuildTree(int[] preorder, int[] inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
if (preorder_left > preorder_right) {
return null;
}
int preorder_root = preorder_left;
int inorder_root = indexMap.get(preorder[preorder_root]);
TreeNode root = new TreeNode(preorder[preorder_root]);
int size_left_subtree = inorder_root - inorder_left;
root.left = myBuildTree(preorder,inorder,preorder_left+1,preorder_left+size_left_subtree,inorder_left,inorder_root-1);
root.right = myBuildTree(preorder, inorder, preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
// 构造哈希映射，帮助我们快速定位根节点
indexMap = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
indexMap.put(inorder[i], i);
}
return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
}


111

例如，给出

3
/ \
9  20
/  \
15   7

class Solution {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();

public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i =0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return helper(inorder, postorder, postorder.length - 1, 0, inorder.length - 1);
}
//postEnd表示
public TreeNode helper(int[] inorder, int[] postorder, int postEnd, int inStart, int inEnd) {
if (inStart > inEnd) {
return null;
}
//获取postorder里面的postEnd坐标的根节点，也就是最前面的根节点
int currentVal = postorder[postEnd];
//放入一个TreeNode中
TreeNode current = new TreeNode(currentVal);
//去存放inorder的hash表中找到这个下标方位inIndex作为分隔左右子树的
int inIndex = map.get(current.val);
current.left = helper(inorder, postorder, postEnd - (inEnd- inIndex) - 1, inStart, inIndex - 1);
current.right = helper(inorder, postorder, postEnd - 1, inIndex + 1, inEnd);
return current;
}
}


11-10 7146

09-14 2万+

03-05 19

10-24 8

03-25 721

04-05 1024

11-03 304

03-23 63

03-15 400

04-20 1867

12-08 607

07-08 3703

03-16 2207

12-08 1075

04-11 2万+

09-03 2万+

04-26 16

05-16 74

11-04 2万+

07-29 1538

04-14 58万+

03-13 14万+

03-04 13万+

03-05 5717

03-08 4万+

03-08 7万+

03-10 12万+

03-12 11万+

03-13 11万+

03-14 1万+

03-18 5432

03-18 8725

03-19 3万+

03-19 8万+

03-20 7488

03-24 3万+

03-25 3万+

05-08 5万+

03-25 9万+

03-29 21万+

03-29 1万+

03-29 10万+

03-30 16万+

05-28 5165

05-28 1万+

04-02 4万+

04-03 3079

04-06 7万+

04-07 5万+

04-09 8万+

04-09 2万+

05-17 7444

04-10 2484

04-11 3万+

04-15 5万+

04-18 4万+

04-20 4万+

04-24 3万+

04-29 5839

04-29 5704

04-30 4585

04-30 8918

04-30 8430

05-16 5万+

05-08 4万+

05-11 3万+

05-12 1万+

05-13 436

05-14 5667

05-14 1508

05-16 1万+

05-20 519

05-18 7658

05-27 567

05-18 2963

05-19 9841

05-21 5653

05-21 5655

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

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试