C语言写出非递归算法中序遍历二叉树
时间: 2023-09-17 22:07:58 浏览: 80
C语言二叉树的非递归遍历实例分析
5星 · 资源好评率100%
以下是C语言非递归算法中序遍历二叉树的实现:
```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;
};
// 栈结构体
struct Stack {
struct StackNode *top;
};
// 初始化栈
void initStack(struct Stack *stack) {
stack->top = NULL;
}
// 入栈
void push(struct Stack *stack, struct TreeNode *node) {
struct StackNode *newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
newNode->node = node;
newNode->next = stack->top;
stack->top = newNode;
}
// 出栈
struct TreeNode* pop(struct Stack *stack) {
if (stack->top == NULL) {
return NULL;
}
struct StackNode *temp = stack->top;
struct TreeNode *node = temp->node;
stack->top = temp->next;
free(temp);
return node;
}
// 中序遍历二叉树
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct Stack stack;
initStack(&stack);
struct TreeNode *node = root;
while (node != NULL || stack.top != NULL) {
while (node != NULL) {
push(&stack, node);
node = node->left;
}
node = pop(&stack);
printf("%d ", node->val);
node = node->right;
}
}
// 测试
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->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
inorderTraversal(root); // 输出:2 1 4 3 5
return 0;
}
```
阅读全文