已知先序序列和中序序列求二叉树用c++实现
时间: 2024-05-10 14:10:24 浏览: 113
以下是用C++实现已知先序序列和中序序列求二叉树的代码:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> inorder_map;
for (int i = 0; i < inorder.size(); i++) {
inorder_map[inorder[i]] = i;
}
return buildTreeHelper(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, inorder_map);
}
TreeNode* buildTreeHelper(vector<int>& preorder, int pre_start, int pre_end, vector<int>& inorder, int in_start, int in_end, unordered_map<int, int>& inorder_map) {
if (pre_start > pre_end || in_start > in_end) {
return nullptr;
}
int root_val = preorder[pre_start];
TreeNode* root = new TreeNode(root_val);
int inorder_root_index = inorder_map[root_val];
int left_subtree_size = inorder_root_index - in_start;
root->left = buildTreeHelper(preorder, pre_start + 1, pre_start + left_subtree_size, inorder, in_start, inorder_root_index - 1, inorder_map);
root->right = buildTreeHelper(preorder, pre_start + left_subtree_size + 1, pre_end, inorder, inorder_root_index + 1, in_end, inorder_map);
return root;
}
};
int main() {
vector<int> preorder = {3, 9, 20, 15, 7};
vector<int> inorder = {9, 3, 15, 20, 7};
Solution solution;
TreeNode* root = solution.buildTree(preorder, inorder);
return 0;
}
```
阅读全文