C语言用栈函数的形式实现二叉树从根节点到每个叶子结点的路径逆序列,用代码显示出来
时间: 2024-05-02 22:20:01 浏览: 132
以下是用C语言实现二叉树从根节点到每个叶子结点的路径逆序列的代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义栈结构体
typedef struct Stack {
int top;
int capacity;
TreeNode **array;
} Stack;
// 初始化栈
Stack *initStack(int capacity) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->top = -1;
stack->capacity = capacity;
stack->array = (TreeNode **)malloc(capacity * sizeof(TreeNode *));
return stack;
}
// 判断栈是否为空
int isStackEmpty(Stack *stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isStackFull(Stack *stack) {
return stack->top == stack->capacity - 1;
}
// 入栈
void push(Stack *stack, TreeNode *node) {
if (isStackFull(stack)) {
printf("Stack is full!\n");
return;
}
stack->array[++stack->top] = node;
}
// 出栈
TreeNode *pop(Stack *stack) {
if (isStackEmpty(stack)) {
printf("Stack is empty!\n");
return NULL;
}
return stack->array[stack->top--];
}
// 反转栈中元素
void reverseStack(Stack *stack) {
if (isStackEmpty(stack)) {
return;
}
TreeNode *node = pop(stack);
reverseStack(stack);
push(stack, node);
}
// 从根节点到叶子结点的路径逆序列
void reversePath(TreeNode *root) {
if (root == NULL) {
return;
}
Stack *stack = initStack(100);
push(stack, root);
while (!isStackEmpty(stack)) {
TreeNode *node = pop(stack);
if (node->left == NULL && node->right == NULL) {
reverseStack(stack);
while (!isStackEmpty(stack)) {
printf("%d ", pop(stack)->val);
}
printf("%d\n", node->val);
}
if (node->right != NULL) {
push(stack, node->right);
}
if (node->left != NULL) {
push(stack, node->left);
}
}
}
// 测试
int main() {
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode *)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode *)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode *)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode *)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
reversePath(root);
return 0;
}
```
阅读全文