求二叉树叶子结点到根节点的路径用栈实现用c语言实现
时间: 2024-04-30 11:18:15 浏览: 104
以下是使用栈实现二叉树叶子结点到根节点路径的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Stack {
TreeNode* data[MAX_STACK_SIZE];
int top;
} Stack;
void push(Stack* stack, TreeNode* node) {
if (stack->top < MAX_STACK_SIZE) {
stack->data[stack->top++] = node;
}
}
TreeNode* pop(Stack* stack) {
if (stack->top > 0) {
return stack->data[--stack->top];
}
return NULL;
}
void printPath(Stack* stack) {
while (stack->top > 0) {
TreeNode* node = pop(stack);
printf("%d ", node->val);
}
printf("\n");
}
void leafToRootPath(TreeNode* root) {
if (!root) {
return;
}
Stack stack;
stack.top = 0;
TreeNode* curr = root;
TreeNode* lastVisited = NULL;
while (curr || stack.top > 0) {
if (curr) {
push(&stack, curr);
curr = curr->left;
} else {
TreeNode* peekNode = stack.data[stack.top - 1];
if (peekNode->right && lastVisited != peekNode->right) {
curr = peekNode->right;
} else {
if (!peekNode->left && !peekNode->right) {
printPath(&stack);
}
lastVisited = pop(&stack);
}
}
}
}
int main() {
/* 构建一棵二叉树 */
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
/* 输出叶子结点到根节点的路径 */
printf("叶子结点到根节点的路径:\n");
leafToRootPath(root);
/* 释放内存 */
free(root->left->left);
free(root->left->right);
free(root->left);
free(root->right->left);
free(root->right->right);
free(root->right);
free(root);
return 0;
}
```
以上代码使用了非递归的方式遍历二叉树,通过栈来保存从根节点到叶子结点的路径,当遍历到叶子结点时,打印出栈中保存的路径即可。
阅读全文