c++写出默克树ABCDE的非递归中序遍历
时间: 2023-06-12 07:07:00 浏览: 125
非递归中序遍历默克树ABCDE的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define LEFT 0
#define RIGHT 1
typedef struct TreeNode {
char data;
struct TreeNode *left, *right;
int flag;
} TreeNode;
typedef struct Stack {
TreeNode* data[MAXSIZE];
int top;
} Stack;
// 初始化栈
void initStack(Stack* s) {
s->top = -1;
}
// 判断栈是否为空
int isStackEmpty(Stack* s) {
return s->top == -1;
}
// 判断栈是否已满
int isStackFull(Stack* s) {
return s->top == MAXSIZE-1;
}
// 入栈
void push(Stack* s, TreeNode* p) {
if (!isStackFull(s)) {
s->data[++s->top] = p;
}
}
// 出栈
TreeNode* pop(Stack* s) {
if (!isStackEmpty(s)) {
return s->data[s->top--];
}
return NULL;
}
// 非递归中序遍历
void inorderTraverse(TreeNode* root) {
Stack s;
TreeNode* p = root;
initStack(&s);
while (p || !isStackEmpty(&s)) {
if (p) {
push(&s, p);
p = p->left;
} else {
p = pop(&s);
if (!p->flag) {
printf("%c ", p->data);
p->flag = RIGHT;
push(&s, p);
p = p->right;
} else {
p = NULL;
}
}
}
}
int main() {
// 构建默克树ABCDE
TreeNode* A = (TreeNode*)malloc(sizeof(TreeNode));
A->data = 'A';
A->left = NULL;
A->right = NULL;
A->flag = LEFT;
TreeNode* B = (TreeNode*)malloc(sizeof(TreeNode));
B->data = 'B';
B->left = NULL;
B->right = NULL;
B->flag = LEFT;
TreeNode* C = (TreeNode*)malloc(sizeof(TreeNode));
C->data = 'C';
C->left = A;
C->right = B;
C->flag = LEFT;
TreeNode* D = (TreeNode*)malloc(sizeof(TreeNode));
D->data = 'D';
D->left = NULL;
D->right = NULL;
D->flag = LEFT;
TreeNode* E = (TreeNode*)malloc(sizeof(TreeNode));
E->data = 'E';
E->left = C;
E->right = D;
E->flag = LEFT;
// 中序遍历
inorderTraverse(E);
return 0;
}
```
输出结果为:A C B E D。
阅读全文