c语言实现二叉树不递归中序遍历的代码,请使用链栈
时间: 2024-05-06 12:21:02 浏览: 74
二叉树的非递归中序遍历 C代码
好的,以下是使用链栈实现二叉树不递归中序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct StackNode {
struct TreeNode *node;
struct StackNode *next;
} StackNode;
void push(StackNode **top, TreeNode *node) {
StackNode *newNode = (StackNode *)malloc(sizeof(StackNode));
newNode->node = node;
newNode->next = *top;
*top = newNode;
}
TreeNode *pop(StackNode **top) {
if (*top == NULL) {
return NULL;
}
StackNode *temp = *top;
*top = (*top)->next;
TreeNode *node = temp->node;
free(temp);
return node;
}
void inOrderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
StackNode *stack = NULL;
TreeNode *node = root;
while (node != NULL || stack != NULL) {
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 = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
inOrderTraversal(root);
return 0;
}
```
当然,如果您有其它更具体的问题,我也可以继续为您解答。
阅读全文