c++写出默克树ABCDE的非递归后序遍历的代码
时间: 2023-06-13 15:05:02 浏览: 94
非递归后序遍历默克树ABCDE的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Stack {
TreeNode* data[MAX_SIZE];
int top;
} Stack;
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
return stack;
}
void push(Stack* stack, TreeNode* node) {
stack->data[++stack->top] = node;
}
TreeNode* pop(Stack* stack) {
return stack->data[stack->top--];
}
int isEmpty(Stack* stack) {
return stack->top == -1;
}
void postorderTraversal(TreeNode* root) {
if (root == NULL)
return;
Stack* stack1 = createStack();
Stack* stack2 = createStack();
push(stack1, root);
while (!isEmpty(stack1)) {
TreeNode* node = pop(stack1);
push(stack2, node);
if (node->left)
push(stack1, node->left);
if (node->right)
push(stack1, node->right);
}
while (!isEmpty(stack2)) {
printf("%c ", pop(stack2)->val);
}
}
int main() {
TreeNode* a = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* b = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* c = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* d = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode* e = (TreeNode*)malloc(sizeof(TreeNode));
a->val = 'A';
b->val = 'B';
c->val = 'C';
d->val = 'D';
e->val = 'E';
a->left = b;
a->right = c;
b->left = d;
b->right = e;
c->left = c->right = d->left = d->right = e->left = e->right = NULL;
printf("Non-recursive postorder traversal: ");
postorderTraversal(a);
printf("\n");
free(a);
free(b);
free(c);
free(d);
free(e);
return 0;
}
```
输出结果为:
```
Non-recursive postorder traversal: E D B C A
```
阅读全文