目录
- 1 遍历二叉树
- 1.1 前序遍历
- 1.2 中序遍历
- 1.3 后序遍历
- 1.3 层序遍历
1 遍历二叉树
1.1 前序遍历
void PreOrder(BTNode* root)
{
if (root == NULL)
{
printf("N ");
return;
}
printf("%d ", root->val);
PreOrder(root->left);
PreOrder(root->right);
}
#include <iostream>
#include <stack>
using namespace std;
struct BTNode {
int val;
BTNode* left;
BTNode* right;
BTNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void PreOrder(BTNode* root) {
if (!root) return;
stack<BTNode*> s;
s.push(root);
while (!s.empty()) {
BTNode* node = s.top();
s.pop();
cout << node->val << " ";
if (node->right) s.push(node->right);
if (node->left) s.push(node->left);
}
}
1.2 中序遍历
void InOrder(BTNode * root)
{
if (root == NULL)
{
printf("N ");
return;
}
InOrder(root->left);
printf("%d ", root->val);
InOrder(root->right);
}
void InOrder(BTNode* root) {
stack<BTNode*> s;
BTNode* curr = root;
while (!s.empty() || curr) {
while (curr) {
s.push(curr);
curr = curr->left;
}
curr = s.top(); s.pop();
cout << curr->val << " ";
curr = curr->right;
}
}
1.3 后序遍历
void PostOrder(BTNode * root)
{
if (root == NULL)
{
printf("N ");
return;
}
InOrder(root->left);
InOrder(root->right);
printf("%d ", root->val);
}
void PostOrder(BTNode* root) {
if (!root) return;
stack<BTNode*> s, output;
s.push(root);
while (!s.empty()) {
BTNode* node = s.top();
s.pop();
output.push(node);
if (node->left) s.push(node->left);
if (node->right) s.push(node->right);
}
while (!output.empty()) {
cout << output.top()->val << " ";
output.pop();
}
}
1.3 层序遍历
#include <iostream>
#include <queue>
using namespace std;
struct BTNode {
char data;
BTNode* left;
BTNode* right;
BTNode(char x) : data(x), left(nullptr), right(nullptr) {}
};
void LevelOrder(BTNode* root) {
if (!root) return;
queue<BTNode*> q;
q.push(root);
while (!q.empty()) {
BTNode* top = q.front();
q.pop();
cout << top->data << " ";
if (top->left) q.push(top->left);
if (top->right) q.push(top->right);
}
}