用c++实现二叉树的前序中序后序遍历
时间: 2023-07-23 22:15:00 浏览: 123
以下是使用C++实现二叉树的前序中序后序遍历的示例代码:
```cpp
#include <iostream>
using namespace std;
// 定义二叉树结点
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 构建二叉树
TreeNode* buildTree(int pre[], int in[], int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return nullptr;
}
int rootVal = pre[preStart];
int rootIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (in[i] == rootVal) {
rootIndex = i;
break;
}
}
int leftLen = rootIndex - inStart;
TreeNode* root = new TreeNode(rootVal);
root->left = buildTree(pre, in, preStart + 1, preStart + leftLen, inStart, rootIndex - 1);
root->right = buildTree(pre, in, preStart + leftLen + 1, preEnd, rootIndex + 1, inEnd);
return root;
}
// 前序遍历
void preOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
int main() {
int pre[] = {1, 2, 4, 5, 3, 6, 7};
int in[] = {4, 2, 5, 1, 6, 3, 7};
TreeNode* root = buildTree(pre, in, 0, 6, 0, 6);
cout << "前序遍历结果:";
preOrder(root);
cout << endl;
cout << "中序遍历结果:";
inOrder(root);
cout << endl;
cout << "后序遍历结果:";
postOrder(root);
cout << endl;
return 0;
}
```
在上面的代码中,我们首先定义了二叉树结点结构体`TreeNode`,然后实现了一个`buildTree`函数,该函数用于根据前序遍历数组和中序遍历数组构建二叉树。接着,我们分别实现了前序遍历、中序遍历和后序遍历的函数,最后在主函数中调用这些函数进行遍历。
阅读全文