c语言非递归中序遍历二叉树
时间: 2023-07-09 15:49:09 浏览: 113
中序遍历二叉树非递归算法
下面是 C 语言非递归中序遍历二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Stack {
TreeNode* data[MAX_STACK_SIZE];
int top;
} Stack;
void push(Stack* s, TreeNode* node) {
if (s->top == MAX_STACK_SIZE - 1) {
printf("Stack overflow!\n");
return;
}
s->data[++s->top] = node;
}
TreeNode* pop(Stack* s) {
if (s->top == -1) {
printf("Stack underflow!\n");
return NULL;
}
return s->data[s->top--];
}
int is_empty(Stack* s) {
return s->top == -1;
}
void inorder_traversal(TreeNode* root) {
if (root == NULL) {
return;
}
Stack s;
s.top = -1;
TreeNode* p = root;
while (p != NULL || !is_empty(&s)) {
while (p != NULL) {
push(&s, p);
p = p->left;
}
if (!is_empty(&s)) {
p = pop(&s);
printf("%d ", p->val);
p = p->right;
}
}
}
int main() {
/*
* 构造一棵二叉树如下:
* 1
* / \
* 2 3
* / \ \
* 4 5 6
*/
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 6;
root->right->right->left = NULL;
root->right->right->right = NULL;
printf("Inorder traversal: ");
inorder_traversal(root);
printf("\n");
return 0;
}
```
输出结果为:
```
Inorder traversal: 4 2 5 1 3 6
```
阅读全文