用c语言采用非递归方法写一个求二叉树上结点的路径
时间: 2023-05-22 08:06:17 浏览: 105
C语言数据结构之二叉树的非递归后序遍历算法
5星 · 资源好评率100%
非常感谢您的问题,这是一道关于二叉树的经典问题。下面是用 C 语言采用非递归方法写一个求二叉树上结点的路径的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义栈数据结构
typedef struct Stack {
TreeNode** nodeArr;
int top;
int size;
} Stack;
// 初始化栈
Stack* initStack(int size) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->nodeArr = (TreeNode**)calloc(size, sizeof(TreeNode*));
stack->top = -1;
stack->size = size;
return stack;
}
// 判断栈是否为空
bool isStackEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
bool isStackFull(Stack* stack) {
return stack->top == stack->size - 1;
}
// 入栈
bool pushStack(Stack* stack, TreeNode* node) {
if (isStackFull(stack)) {
return false;
}
stack->nodeArr[++stack->top] = node;
return true;
}
// 出栈
TreeNode* popStack(Stack* stack) {
if (isStackEmpty(stack)) {
return NULL;
}
return stack->nodeArr[stack->top--];
}
// 栈顶元素
TreeNode* topStack(Stack* stack) {
if (isStackEmpty(stack)) {
return NULL;
}
return stack->nodeArr[stack->top];
}
// 二叉树路径遍历
void pathTraversal(TreeNode* root, TreeNode* target) {
if (root == NULL || target == NULL) {
return;
}
Stack* stack = initStack(100);
TreeNode* cur = root;
TreeNode* last = NULL;
while (cur != NULL || !isStackEmpty(stack)) {
if (cur) {
pushStack(stack, cur);
if (cur == target) {
printf("找到了目标节点\n");
printf("路径是:");
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->nodeArr[i]->val);
}
printf("\n");
break;
}
cur = cur->left;
} else {
TreeNode* top = topStack(stack);
if (top->right && top->right != last) {
cur = top->right;
} else {
last = popStack(stack);
}
}
}
}
int main() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 4;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 5;
root->right->right->left = NULL;
root->right->right->right = NULL;
pathTraversal(root, root->right->left);
return 0;
}
```
此代码将从给定的二叉树中查找给定的节点,并输出到根节点的路径。这种方法使用了栈来进行非递归式的遍历,并通过输出栈中所有元素的值来打印路径。
希望这个示例代码可以帮助您解决这个问题,感谢您的提问!
阅读全文