用c语言或C++再写一遍
时间: 2024-11-22 11:44:40 浏览: 13
当然,这里是使用C++编写的一个简单版本,用于根据先序遍历(preorder)和中序遍历(inorder)构建二叉树并输出后序遍历(postorder)和层次遍历(level order):
```cpp
#include <iostream>
#include <vector>
// 定义二叉树节点结构
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 根据前序和中序遍历来构造二叉树
TreeNode* buildTree(std::string preorder[], std::string inorder[], int preStart, int inStart, int inEnd) {
if (preStart >= inEnd || preStart > inEnd) {
return nullptr;
}
// 找到当前节点在中序数组中的位置
int index = -1;
for (int i = inStart; i <= inEnd; ++i) {
if (inorder[i] == preorder[preStart]) {
index = i;
break;
}
}
// 构建当前节点
TreeNode* node = new TreeNode(preorder[preStart]);
// 更新指针并继续构造子树
node->left = buildTree(preorder, inorder, preStart + 1, inStart, index);
node->right = buildTree(preorder, inorder, preStart + index - inStart + 1, index + 1, inEnd);
return node;
}
// 后序遍历
std::vector<int> postOrderTraversal(TreeNode* root) {
std::vector<int> res;
if (root != nullptr) {
res = postOrderTraversal(root->left) + postOrderTraversal(root->right) + {root->val};
}
return res;
}
// 层次遍历
std::vector<std::pair<int, int>> levelOrderTraversal(TreeNode* root) {
std::vector<std::pair<int, int>> res;
if (root != nullptr) {
std::queue<std::pair<TreeNode*, int>> q {{root, 0}};
while (!q.empty()) {
auto [node, depth] = q.front();
res.push_back({node->val, depth});
q.pop();
if (node->left) {
q.push({node->left, depth + 1});
}
if (node->right) {
q.push({node->right, depth + 1});
}
}
}
return res;
}
int main() {
std::string preorder[] = {"abdeijfcgh"};
std::string inorder[] = {"dijefbghca"};
TreeNode* root = buildTree(preorder, inorder, 0, 0, sizeof(inorder) - 1);
std::vector<int> postorder = postOrderTraversal(root);
std::vector<std::pair<int, int>> levelorder = levelOrderTraversal(root);
std::cout << "后序遍历序列: ";
for (int val : postorder) {
std::cout << val << " ";
}
std::cout << "\n";
std::cout << "层次遍历序列: ";
for (const auto& pair : levelorder) {
std::cout << "{" << pair.first << ", " << pair.second << "} ";
}
std::cout << "\n";
return 0;
}
```
这个程序首先创建了一个二叉树,然后分别计算了后序遍历和层次遍历的结果。注意这里假设输入的字符串已经被转换为整数数组。在实际应用中,你可能需要额外处理字符串到整数的转换。
阅读全文