c语言用非递归实现二叉树的前序、中序、后序遍历算法。 注意:非递归算法写前序、中序、后序遍历算法
时间: 2023-06-27 19:02:57 浏览: 116
C语言实现二叉树的前序、中序、后续遍历非递归法.doc
二叉树的前序、中序、后序遍历算法可以使用栈来实现非递归遍历。
以前序遍历为例:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct StackNode {
struct TreeNode* node;
struct StackNode* next;
};
void push(struct StackNode** stack, struct TreeNode* node) {
struct StackNode* new_node = (struct StackNode*)malloc(sizeof(struct StackNode));
new_node->node = node;
new_node->next = *stack;
*stack = new_node;
}
struct TreeNode* pop(struct StackNode** stack) {
if (*stack == NULL) {
return NULL;
}
struct StackNode* top = *stack;
struct TreeNode* node = top->node;
*stack = top->next;
free(top);
return node;
}
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct TreeNode* node;
struct StackNode* stack = NULL;
push(&stack, root);
while (stack != NULL) {
node = pop(&stack);
printf("%d ", node->val);
if (node->right != NULL) {
push(&stack, node->right);
}
if (node->left != NULL) {
push(&stack, node->left);
}
}
}
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct TreeNode* node = root;
struct StackNode* stack = NULL;
while (node != NULL || stack != NULL) {
while (node != NULL) {
push(&stack, node);
node = node->left;
}
node = pop(&stack);
printf("%d ", node->val);
node = node->right;
}
}
void postorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct TreeNode* node = root;
struct TreeNode* last_visited = NULL;
struct StackNode* stack = NULL;
while (node != NULL || stack != NULL) {
while (node != NULL) {
push(&stack, node);
node = node->left;
}
node = stack->node;
if (node->right == NULL || node->right == last_visited) {
printf("%d ", node->val);
pop(&stack);
last_visited = node;
node = NULL;
} else {
node = node->right;
}
}
}
int main() {
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
struct TreeNode* node1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node1->val = 2;
struct TreeNode* node2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node2->val = 3;
struct TreeNode* node3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node3->val = 4;
struct TreeNode* node4 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node4->val = 5;
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
node2->left = NULL;
node2->right = NULL;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
printf("Postorder Traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
对于中序遍历和后序遍历,只需要修改遍历顺序即可。
阅读全文