利用链接栈实现二叉树的前序遍历的全代码C++
时间: 2023-05-29 09:03:52 浏览: 79
二叉树的前序遍历(C++)
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct TreeNode {
char value;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode *data[MAXSIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, TreeNode *node) {
if (s->top == MAXSIZE - 1) {
printf("Stack overflow\n");
return;
}
s->top++;
s->data[s->top] = node;
}
TreeNode *pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
return NULL;
}
TreeNode *node = s->data[s->top];
s->top--;
return node;
}
TreeNode *createTreeNode(char value) {
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
TreeNode *createBinaryTree(char *s, int *index) {
if (s[*index] == '\0') {
return NULL;
}
if (s[*index] == '#') {
(*index)++;
return NULL;
}
TreeNode *node = createTreeNode(s[*index]);
(*index)++;
node->left = createBinaryTree(s, index);
(*index)++;
node->right = createBinaryTree(s, index);
return node;
}
void preOrderTraversalWithStack(TreeNode *root) {
if (root == NULL) {
return;
}
Stack s;
initStack(&s);
push(&s, root);
while (s.top != -1) {
TreeNode *node = pop(&s);
printf("%c ", node->value);
if (node->right != NULL) {
push(&s, node->right);
}
if (node->left != NULL) {
push(&s, node->left);
}
}
}
int main() {
char s[] = "AB#D##C##";
int index = 0;
TreeNode *root = createBinaryTree(s, &index);
printf("Pre-order traversal with stack: ");
preOrderTraversalWithStack(root);
printf("\n");
return 0;
}
```
阅读全文