用c++实现二叉树的非递归遍历
时间: 2023-12-10 20:51:00 浏览: 74
c++实现二叉树的4种遍历(递归和非递归)(csdn)————程序.pdf
好的,下面是用C语言实现二叉树的中序遍历的非递归算法:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct TreeNode {
int value;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
void inorderTraversal(TreeNode *root) {
TreeNode *stack[MAX_STACK_SIZE];
int top = -1;
while (1) {
while (root) {
stack[++top] = root;
root = root->left;
}
if (top == -1) {
break;
}
root = stack[top--];
printf("%d ", root->value);
root = root->right;
}
}
int main() {
TreeNode *node1 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node2 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node3 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node4 = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *node5 = (TreeNode*)malloc(sizeof(TreeNode));
node1->value = 1;
node2->value = 2;
node3->value = 3;
node4->value = 4;
node5->value = 5;
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = node5;
node3->left = NULL;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
inorderTraversal(node1);
free(node1);
free(node2);
free(node3);
free(node4);
free(node5);
return 0;
}
```
该算法使用一个栈来模拟递归遍历过程,遍历顺序从顶部到底部,即先遍历左子树,再遍历根节点,最后遍历右子树。
阅读全文