C++实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式。
1. 二叉树的基本结构
struct Node {
int value;
Node* left;
Node* right;
Node(int value):
value(value), left(nullptr), right(nullptr) {}
};
2. 递归和非递归方式
2.1 递归方式
递归方式没有什么好说的。
2.2 非递归方式
这里的实现细节可以参考这篇博客: 二叉树几种遍历算法的非递归实现 具体的细节还是比较好理解的。
3. 代码
程序说明:
preOrderRecur
递归方式实现先序遍历inOrderRecur
递归方式实现中序遍历posOrderRecur
递归方式实现后序遍历preOrderUnRecur
非递归方式实现先序遍历inOrderUnRecur
非递归方式实现中序遍历posOrderUnRecur
非递归方式实现后序遍历
完整代码:
#include <iostream>
#include <stack>
struct Node {
int value;
Node* left;
Node* right;
Node(int value):
value(value), left(nullptr), right(nullptr) {}
};
void preOrderRecur(Node* head) {
if (head == nullptr) {
return;
}
std::cout << head->value << ",";
preOrderRecur(head->left);
preOrderRecur(head->right);
}
void inOrderRecur(Node* head) {
if (head == nullptr) {
return;
}
inOrderRecur(head->left);
std::cout << head->value << ",";
inOrderRecur(head->right);
}
void posOrderRecur(Node* head) {
if (head == nullptr) {
return;
}
posOrderRecur(head->left);
posOrderRecur(head->right);
std::cout << head->value << ",";
}
void preOrderUnRecur(Node* head) {
if (head == nullptr) {
return;
}
std::stack<Node*> nstack;
nstack.push(head);
while(!nstack.empty()) {
Node* head = nstack.top(); // get stack top
std::cout << head->value << ",";
nstack.pop();
if (head->right != nullptr) {
nstack.push(head->right);
}
if (head->left != nullptr) {
nstack.push(head->left);
}
}
}
void inOrderUnRecur(Node* head) {
if (head == nullptr) {
return;
}
std::stack<Node*> nstack;
while (!nstack.empty() || head != nullptr) {
if (head != nullptr) {
nstack.push(head);
head = head->left;
} else {
head = nstack.top();
std::cout << head->value << ",";
nstack.pop();
head = head->right;
}
}
}
void posOrderUnRecur(Node* head) {
if (head == nullptr) {
return;
}
std::stack<Node*> nstack1, nstack2;
nstack1.push(head);
while (!nstack1.empty()) {
Node* head = nstack1.top();
nstack2.push(head);
nstack1.pop();
if (head->left != nullptr) {
nstack1.push(head->left);
}
if (head->right != nullptr) {
nstack1.push(head->right);
}
}
while (!nstack2.empty()) {
std::cout << nstack2.top()->value << ",";
nstack2.pop();
}
}
int main() {
Node* head = new Node(5);
head->left = new Node(3);
head->right = new Node(8);
head->left->left = new Node(2);
head->left->right = new Node(4);
head->right->left = new Node(7);
head->right->right = new Node(10);
head->right->left->left = new Node(6);
head->right->right->left = new Node(9);
head->right->right->right = new Node(11);
std::cout << "==============recursive==============";
std::cout << "\npre-order: ";
preOrderRecur(head);
std::cout << "\nin-order: ";
inOrderRecur(head);
std::cout << "\npos-order: ";
posOrderRecur(head);
std::cout << "\n==============un-recursive==============";
std::cout << "\npre-order: ";
preOrderUnRecur(head);
std::cout << "\nin-order: ";
inOrderUnRecur(head);
std::cout << "\npos-order: ";
posOrderUnRecur(head);
return 0;
}