c语言用堆栈实现二叉树的前序遍历
时间: 2023-05-30 21:01:57 浏览: 52
c实现二叉树先序层序遍历
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
TreeNode *data[STACK_SIZE];
int top;
} Stack;
void init(Stack *stack) {
stack->top = -1;
}
int isEmpty(Stack *stack) {
return stack->top == -1;
}
int isFull(Stack *stack) {
return stack->top == STACK_SIZE - 1;
}
void push(Stack *stack, TreeNode *node) {
if (isFull(stack)) {
printf("Stack is full.\n");
return;
}
stack->data[++stack->top] = node;
}
TreeNode *pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return NULL;
}
return stack->data[stack->top--];
}
TreeNode *createNode(int val) {
TreeNode *node = (TreeNode *) malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
TreeNode *createTree() {
TreeNode *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
return root;
}
void preOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Stack stack;
init(&stack);
push(&stack, root);
while (!isEmpty(&stack)) {
TreeNode *node = pop(&stack);
printf("%d ", node->val);
if (node->right != NULL) {
push(&stack, node->right);
}
if (node->left != NULL) {
push(&stack, node->left);
}
}
}
int main() {
TreeNode *root = createTree();
printf("Preorder traversal: ");
preOrder(root);
return 0;
}
阅读全文