二叉树的先中后序遍历非递归用c语言实现
时间: 2023-10-24 22:07:01 浏览: 101
自己编写的实验二叉树的后序遍历非递归算法c语言实现
5星 · 资源好评率100%
好的,针对您的问题,下面是二叉树的先中后序遍历非递归算法的 C 语言实现:
先序遍历:
```c
void preorderTraversal(struct TreeNode* root, int* returnSize) {
int top = -1, i;
struct TreeNode* stack[100];
*returnSize = 0;
if (!root) {
return;
}
stack[++top] = root;
while (top != -1) {
root = stack[top--];
(*returnSize)++;
stack[++top] = root->right;
stack[++top] = root->left;
}
}
```
中序遍历:
```c
void inorderTraversal(struct TreeNode* root, int* returnSize) {
int top = -1, i;
struct TreeNode* stack[100];
*returnSize = 0;
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
if (top != -1) {
(*returnSize)++;
root = stack[top--];
stack[++top] = root->right;
}
}
}
```
后序遍历:
```c
void postorderTraversal(struct TreeNode* root, int* returnSize) {
int top = -1, i;
struct TreeNode* stack[100], *lastVisited = NULL;
*returnSize = 0;
while (root || top != -1) {
while (root) {
stack[++top] = root;
root = root->left;
}
root = stack[top];
if (!root->right || root->right == lastVisited) {
(*returnSize)++;
top--;
lastVisited = root;
root = NULL;
} else {
root = root->right;
stack[++top] = root;
}
}
}
```
希望这些代码可以解决您的问题。
阅读全文