c++建立一个二叉树用前序后序以及中序遍历法输出
时间: 2023-07-01 19:15:47 浏览: 104
好的,下面是一个基于前序、中序和后序遍历结果构建二叉树,并输出前序、中序和后序遍历结果的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义二叉树节点结构体
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
// 根据前序、中序和后序遍历结果构造二叉树
TreeNode* buildTree(vector<char>& preorder, vector<char>& inorder, vector<char>& postorder, int pre_start, int pre_end, int in_start, int in_end, int post_start, int post_end) {
if (pre_start > pre_end || in_start > in_end || post_start > post_end) return NULL;
TreeNode* root = new TreeNode(preorder[pre_start]);
int index = 0;
for (int i = in_start; i <= in_end; i++) {
if (inorder[i] == root->val) {
index = i;
break;
}
}
int left_len = index - in_start;
root->left = buildTree(preorder, inorder, postorder, pre_start + 1, pre_start + left_len, in_start, index - 1, post_start, post_start + left_len - 1);
root->right = buildTree(preorder, inorder, postorder, pre_start + left_len + 1, pre_end, index + 1, in_end, post_start + left_len, post_end - 1);
return root;
}
// 输出前序遍历结果
void preorderTraversal(TreeNode* root) {
if (root == NULL) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 输出中序遍历结果
void inorderTraversal(TreeNode* root) {
if (root == NULL) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 输出后序遍历结果
void postorderTraversal(TreeNode* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
int main() {
vector<char> preorder = {'A', 'B', 'D', 'E', 'C', 'F'};
vector<char> inorder = {'D', 'B', 'E', 'A', 'F', 'C'};
vector<char> postorder = {'D', 'E', 'B', 'F', 'C', 'A'};
TreeNode* root = buildTree(preorder, inorder, postorder, 0, preorder.size() - 1, 0, inorder.size() - 1, 0, postorder.size() - 1);
cout << "前序遍历结果为:";
preorderTraversal(root);
cout << endl;
cout << "中序遍历结果为:";
inorderTraversal(root);
cout << endl;
cout << "后序遍历结果为:";
postorderTraversal(root);
return 0;
}
```
输出结果为:
```
前序遍历结果为:A B D E C F
中序遍历结果为:D B E A F C
后序遍历结果为:D E B F C A
```
分别为前序、中序和后序遍历结果。
阅读全文