0%

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

可知中序遍历序列的首位为根节点,而中序遍历的序列中,根节点分隔左、右子树,故可在中序遍历的序列中查找根节点,即得到表示左、右子树的序列,递归至序列长度不大于1。

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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode *root = nullptr;
if (pre.size() == 0)
{
root = nullptr;
}
else
{
const int root_val = pre[0];
auto it = vin.begin();
int left_size = 0;
root = new TreeNode(root_val);
while (*it != root_val)
{
it++;
left_size++;
}
root->left = reConstructBinaryTree(
vector<int>(pre.begin() + 1, pre.begin() + left_size + 1),
vector<int>(vin.begin(), it));
root->right = reConstructBinaryTree(
vector<int>(pre.begin() + 1 + left_size, pre.end()),
vector<int>(it + 1, vin.end()));
}
return root;
}
};