c++写出默克树ABCDE的非递归前序遍历
时间: 2024-01-13 19:03:46 浏览: 72
非递归前序遍历默克树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;
TreeNode* createNode(char val) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void push(Stack *stack, TreeNode *node) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
return;
}
stack->data[++stack->top] = node;
}
TreeNode* pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack underflow\n");
return NULL;
}
return stack->data[stack->top--];
}
void preorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Stack stack;
stack.top = -1;
push(&stack, root);
while (stack.top != -1) {
TreeNode *node = pop(&stack);
printf("%c ", node->val);
if (node->right != NULL) {
push(&stack, node->right);
}
if (node->left != NULL) {
push(&stack, node->left);
}
}
}
int main() {
TreeNode *A = createNode('A');
TreeNode *B = createNode('B');
TreeNode *C = createNode('C');
TreeNode *D = createNode('D');
TreeNode *E = createNode('E');
A->left = B;
A->right = C;
B->left = D;
C->left = E;
printf("Preorder traversal of the Merkle tree: ");
preorderTraversal(A);
return 0;
}
```
输出结果为:`A B D C E`
阅读全文