c语言完整代码遍历二叉树
时间: 2024-11-04 22:08:53 浏览: 16
当然,下面是C语言非递归遍历二叉树的完整代码示例。这里我们使用了栈数据结构来实现中序遍历和后序遍历:
### 中序遍历(非递归)
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 插入节点到堆栈
void push(Node* node, stack_type* s) {
s->top++;
s->stack[s->top] = node;
}
// 弹出并返回顶部节点
TreeNode* pop(stack_type* s) {
if(s->top == -1)
return NULL;
else {
TreeNode* temp = s->stack[s->top];
s->top--;
return temp;
}
}
// 中序遍历
void inOrderTraversal(TreeNode* root) {
stack_type s; // 声明一个栈
s.top = -1;
TreeNode* curr = root;
while(curr || !s.isEmpty()) { // 循环直到整个树都被访问过
while(curr) { // 当前节点不为空
push(curr, &s);
curr = curr->left;
}
curr = pop(&s); // 弹出栈顶节点作为当前节点
printf("%d ", curr->val); // 访问节点
curr = curr->right; // 转向右子树
}
}
// 创建和测试树节点
int main() {
// 示例:创建一棵简单的二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
inOrderTraversal(root); // 中序遍历
return 0;
}
阅读全文