二叉树的层序遍历先序遍历中序遍历后序遍历非递归算法代码
时间: 2024-06-17 15:01:20 浏览: 122
当然,二叉树的遍历有三种主要方式:先序遍历(根-左-右)、中序遍历(左-根-右)和后序遍历(左-右-根)。非递归的层次遍历(也叫广度优先遍历,从上到下、从左到右)通常使用队列来辅助实现。
这里分别给出这些遍历的非递归算法代码:
1. 层序遍历(广度优先遍历):
```c
#include <stdio.h>
#include <stdlib.h>
#include <queue>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void levelOrder(struct TreeNode* root) {
if (root == NULL) return;
// 使用队列存储每一层的节点
queue<struct TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
struct TreeNode* node = q.front();
q.pop();
printf("%d ", node->val); // 打印当前节点值
if (node->left != NULL) q.push(node->left);
if (node->right != NULL) q.push(node->right);
}
printf("\n"); // 换行表示新的一层
}
}
```
2. 先序遍历(递归和非递归两种方式,这里是非递归版本,使用栈):
```c
void preorderNonRecursive(struct TreeNode* root) {
if (root == NULL) return;
stack<struct TreeNode*> s;
s.push(root);
while (!s.empty()) {
struct TreeNode* node = s.top();
s.pop();
printf("%d ", node->val); // 打印当前节点值
if (node->right != NULL) s.push(node->right);
if (node->left != NULL) s.push(node->left);
}
}
```
3. 中序遍历(非递归,同样使用栈):
```c
void inorderNonRecursive(struct TreeNode* root) {
if (root == NULL) return;
stack<struct TreeNode*> s;
struct TreeNode* curr = root;
while (curr != NULL || !s.empty()) {
while (curr != NULL) {
s.push(curr);
curr = curr->left;
}
curr = s.top();
s.pop();
printf("%d ", curr->val); // 打印当前节点值
curr = curr->right;
}
}
```
4. 后序遍历(非递归,使用两个栈):
```c
void postorderNonRecursive(struct TreeNode* root) {
if (root == NULL) return;
stack<struct TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
struct TreeNode* node = s1.top();
s1.pop();
s2.push(node);
if (node->left != NULL) s1.push(node->left);
if (node->right != NULL) s1.push(node->right);
}
while (!s2.empty()) {
struct TreeNode* node = s2.top();
s2.pop();
printf("%d ", node->val); // 打印当前节点值
}
}
```
阅读全文