二叉树的遍历算法c语言
时间: 2023-11-28 15:45:08 浏览: 95
以下是C语言实现二叉树遍历的迭代算法,包括二叉树的中序遍历、先序遍历及后序遍历等:
1. 二叉树的中序遍历
```c
void inorderTraversal(struct TreeNode* root){
struct TreeNode* stack[100]; int top = -1;
struct TreeNode* p = root;
while(p || top != -1){
while(p){
stack[++top] = p;
p = p->left;
}
p = stack[top--];
printf("%d ", p->val);
p = p->right;
}
}
```
2. 二叉树的先序遍历
```c
void preorderTraversal(struct TreeNode* root){
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* p = root;
while(p || top != -1){
while(p){
printf("%d ", p->val);
stack[++top] = p;
p = p->left;
}
p = stack[top--];
p = p->right;
}
}
```
3. 二叉树的后序遍历
```c
void postorderTraversal(struct TreeNode* root){
struct TreeNode* stack[100];
int top = -1;
struct TreeNode* p = root;
struct TreeNode* lastVisit = NULL;
while(p || top != -1){
while(p){
stack[++top] = p;
p = p->left;
}
p = stack[top];
if(p->right == NULL || p->right == lastVisit){
printf("%d ", p->val);
top--;
lastVisit = p;
p = NULL;
}else{
p = p->right;
}
}
}
```
阅读全文