LC.P106[从中序与后序遍历序列构造二叉树]

方法一:DFS+哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int[] inorder;
int[] postorder;
Map<Integer, Integer> map = new HashMap<>();

public TreeNode buildTree(int[] inorder, int[] postorder) {
this.inorder = inorder;
this.postorder = postorder;
int n = inorder.length;
for (int i = 0; i < n; ++i) {
map.put(inorder[i], i);
}
return build(0, n - 1, 0, n - 1);
}

private TreeNode build(int postorderLeft, int postorderRight, int inorderLeft, int inorderRight) {
if (postorderLeft > postorderRight) return null;
int inorderRoot = map.get(postorder[postorderRight]); // 在中序遍历中定位根节点
TreeNode root = new TreeNode(postorder[postorderRight]);
int leftSubTreeSize = inorderRoot - inorderLeft; // 左子树大小
root.left = build(postorderLeft, postorderLeft + leftSubTreeSize - 1, inorderLeft, inorderRoot - 1);
root.right = build(postorderLeft + leftSubTreeSize, postorderRight - 1, inorderRoot + 1, inorderRight);
return root;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$