试着用C语言写一个二叉树后序遍历的非递归算法。
时间: 2024-05-04 07:21:02 浏览: 104
以下是用C语言实现二叉树后序遍历的非递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct Stack {
struct TreeNode *data[100];
int top;
};
void push(struct Stack *s, struct TreeNode *node) {
if (s->top == 99) {
printf("Stack overflow\n");
return;
}
s->data[++s->top] = node;
}
struct TreeNode *pop(struct Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
return NULL;
}
return s->data[s->top--];
}
int isEmpty(struct Stack *s) {
return s->top == -1;
}
void postorderTraversal(struct TreeNode *root) {
if (root == NULL) {
return;
}
struct Stack s1, s2;
s1.top = -1;
s2.top = -1;
push(&s1, root);
while (!isEmpty(&s1)) {
struct TreeNode *node = pop(&s1);
push(&s2, node);
if (node->left) {
push(&s1, node->left);
}
if (node->right) {
push(&s1, node->right);
}
}
while (!isEmpty(&s2)) {
printf("%d ", pop(&s2)->val);
}
}
int main() {
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = NULL;
root->left->right = NULL;
root->right->left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("Postorder traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
这个算法使用了两个栈s1和s2,其中s1用于辅助遍历二叉树,s2用于存储遍历结果。具体思路如下:
1. 将根节点入栈s1。
2. 取出s1栈顶元素node,并将node入栈s2。
3. 如果node的左子树非空,将左子树入栈s1。
4. 如果node的右子树非空,将右子树入栈s1。
5. 重复步骤2至4,直到s1为空。
6. 从s2中依次弹出元素,即为后序遍历结果。
值得注意的是,由于后序遍历的顺序是左右根,因此在第2步中需要先将node入栈s2,再将右子树入栈s1,最后才将左子树入栈s1,以保证得到正确的遍历结果。
阅读全文