用C语言编写一个能运行的中序遍历二叉树T的非递归算法
时间: 2023-09-12 11:05:12 浏览: 76
中序遍历二叉树非递归算法
好的,下面是用C语言编写的中序遍历二叉树的非递归算法:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
void inorderTraversal(struct TreeNode* root) {
struct TreeNode* stack[1000];
int top = -1;
struct TreeNode* node = root;
while (node || top != -1) {
while (node) {
stack[++top] = node;
node = node->left;
}
node = stack[top--];
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);
return 0;
}
```
其中,stack数组是用来存储待访问的节点的,top是栈顶指针,node是当前访问的节点。算法的思路是,先把当前节点的所有左子树节点入栈,然后访问栈顶节点并出栈,最后访问栈顶节点的右子树。重复这个过程直到栈为空。
阅读全文