递归遍历搜索二叉树的叶子节点并输出从根节点到该叶子节点的路径
构建一个二叉树:
查找叶子节点 f,并输出从根节点到叶子节点的路径。
#include <stdio.h>
#include <stdlib.h>
typedef struct node *Nd; //定义结构体指针
struct node { //结构体
char data;
Nd left;
Nd right;
};
//创建新的节点
Nd createNode(char data) {
Nd newNode = (Nd)malloc(sizeof(node));
if (newNode == NULL) {
printf("内存分配失败");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
//查找叶子节点,函数的递归调用
int searchLeafNode(Nd root, char target, Nd path[], int pathLen){
if (root == NULL) return 0;
path[pathLen] = root;
pathLen++;
if (root->left == NULL && root->right == NULL) {
if (root->data == target) {
printf("叶子结点:%c 的路径为:", target);
for (int i = 0; i < pathLen; i++) {
printf("%c ", path[i]->data);
}
putchar('\n');
return 1;
}
}
if (searchLeafNode(root->left, target, path, pathLen)) return 1;
if (searchLeafNode(root->right, target, path, pathLen)) return 1;
return 0;
}
int main(void) {
//简单构建一个二叉树
Nd root = createNode('a');
root->left = createNode('b');
root->right = createNode('c');
root->left->left = createNode('e');
root->left->right = createNode('d');
root->left->right->right = createNode('f');
Nd path[8];
int pathLen = 0;
if (!searchLeafNode(root, 'f', path, pathLen))
printf("没有找到该叶子节点!\n");
return 0;
}
运行:
对于更加复杂的二叉树都可以用这种方法来查找叶子结点,并输出其路径。