二叉树非递归遍历c语言
时间: 2023-11-14 19:11:27 浏览: 88
二叉树的非递归遍历可以使用栈来实现。以下是C语言的实现思路:
1. 将树的所有节点标志位置为假(0),并将根节点压入栈中进入循环。
2. 只要栈中元素个数大于0,进行循环操作弹出栈顶元素。
3. 如果栈顶元素标志为真,直接输出,进行下次循环即可。
4. 如果栈顶元素标志为假,将标志改为真,并将栈顶节点的右子树、根、左子树压入栈中,再执行下次循环。
以下是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode **data;
int top;
int size;
} Stack;
Stack *createStack(int size) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->data = (TreeNode **)malloc(sizeof(TreeNode *) * size);
stack->top = -1;
stack->size = size;
return stack;
}
void push(Stack *stack, TreeNode *node) {
if (stack->top == stack->size - 1) {
return;
}
stack->top++;
stack->data[stack->top] = node;
}
TreeNode *pop(Stack *stack) {
if (stack->top == -1) {
return NULL;
}
TreeNode *node = stack->data[stack->top];
stack->top--;
return node;
}
void inorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Stack *stack = createStack(100);
TreeNode *node = root;
while (node != NULL || stack->top != -1) {
while (node != NULL) {
push(stack, node); node = node->left;
}
node = pop(stack);
printf("%d ", node->val);
node = node->right;
}
}
int main() {
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = 1; root->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = NULL;
inorderTraversal(root);
return 0;
}
```
阅读全文