#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();
}
}
二叉树遍历(C++)
最新推荐文章于 2024-06-13 10:42:22 发布