前序遍历:根左右
中序遍历:左根右
后序遍历:左右根
#include <iostream>
#include <vector>
using namespace std;
//双链表节点结构
typedef struct treeNode {
int value;
struct treeNode* left;
struct treeNode* right;
treeNode(int x) : value(x), left(nullptr), right(nullptr) {}
} Node;
//前序遍历
void preOrder(Node* root, vector<int> &allval)
{
if (!root)
{
return;
}
allval.push_back(root->value); //遍历根节点
preOrder(root->left, allval); //遍历左节点
preOrder(root->right, allval); //遍历右节点
}
//中序遍历
void inOrder(Node* root, vector<int> &allval)
{
if (!root)
{
return;
}
inOrder(root->left, allval); //遍历左节点
allval.push_back(root->value); //遍历根节点
inOrder(root->right, allval); //遍历右节点
}
//后序遍历
void postOrder(Node* root, vector<int> &allval)
{
if (!root)
{
return;
}
postOrder(root->left, allval); //遍历左节点
postOrder(root->right, allval); //遍历右节点
allval.push_back(root->value); //遍历根节点
}
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
// 1
// 2 3
// 4 5
cout << "前序遍历结果:" << endl; //12453
vector<int> ves;
preOrder(root, ves);
for (int i = 0; i < ves.size(); i++)
{
cout << ves.at(i) << " ";
}
cout << endl;
cout << "中序遍历结果:" << endl; //42513
vector<int> ves1;
inOrder(root, ves1);
for (int i = 0; i < ves1.size(); i++)
{
cout << ves1.at(i) << " ";
}
cout << endl;
cout << "后序遍历结果:" << endl; //45231
vector<int> ves2;
postOrder(root, ves2);
for (int i = 0; i < ves2.size(); i++)
{
cout << ves2.at(i) << " ";
}
cout << endl;
system("pause");
return 0;
}