1. 利用先序的遍历方法创建一棵二叉树 2..利用栈,采用先序非递归算法遍历一个二叉树,输出其遍历结果。 3. 利用栈,采用中序非递归算法遍历一个二叉树,输出其遍历结果。 4.利用栈,采用后序非递归算法遍历一个二叉树,输出其遍历结果。 用c语言写上面这个代码,具体一点
时间: 2025-01-20 15:14:39 浏览: 47
在C语言中,我们可以使用递归或栈来实现二叉树的先序、中序和后序遍历。这里是一个简单的栈非递归版本的代码示例,假设我们已经有一个`struct TreeNode`来表示二叉树节点:
首先,我们需要三个辅助函数,分别对应三种遍历顺序:
1. 先序遍历(根-左-右)
2. 中序遍历(左-根-右)
3. 后序遍历(左-右-根)
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 遍历函数,使用栈保存遍历路径
void inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
TreeNode* current = root;
while (current != NULL || !s.empty()) {
while (current != NULL) {
s.push(current);
current = current->left;
}
current = s.top();
s.pop();
printf("%d ", current->val); // 输出当前节点值
current = current->right;
}
}
void preorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
printf("%d ", node->val); // 输出当前节点值
if (node->right) s.push(node->right);
if (node->left) s.push(node->left);
s.pop();
}
}
void postorderTraversal(TreeNode* root) {
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* node = s1.top();
s1.pop();
s2.push(node);
if (node->left) s1.push(node->left);
if (node->right) s1.push(node->right);
}
while (!s2.empty()) {
printf("%d ", s2.top()->val);
s2.pop();
}
}
```
阅读全文
相关推荐

















