Keshawn_lu's Blog

Leetcode 106. 从中序与后序遍历序列构造二叉树

字数统计: 397阅读时长: 1 min
2020/09/25 Share

题目简介:

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

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

例如,给出

1
2
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

思路:

我们首先将每个结点在中序遍历中的位置存储下来。

因为后序遍历的顺序为左右根,所以从后序遍历的最后一个结点开始遍历(树的根节点)。

每次根据后序遍历遍历到的结点去找出该结点在中序遍历中的位置,然后递归即可。

tip:

  • 由于后序遍历是左右根,所以递归时是先构建右子树,再构建左子树。(从后往前)

代码如下:

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
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:

unordered_map<int, int> map;
int post_id;

TreeNode* dfs(int in_left, int in_right, vector<int>& postorder){

if(in_left > in_right)
return NULL;

int root_val = postorder[post_id];

TreeNode* root = new TreeNode(root_val);

int index = map[root_val]; //找到该根节点在中序遍历中的位置

post_id--; //下一个根节点

root -> right = dfs(index + 1, in_right, postorder); //先右子树
root -> left = dfs(in_left, index - 1, postorder);

return root;
}

TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {

post_id = postorder.size() - 1; //最后一个为第一个根节点

for(int i = 0; i < inorder.size(); i++){

map[inorder[i]] = i; //记录各个节点在中序遍历中的位置
}

return dfs(0, inorder.size() - 1, postorder);
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: