在二叉树中查找指定值结点的所有祖先
#include<stdio.h> #include<stdlib.h> //用二叉链表存储方式建树(完全二叉树) typedef struct BitTree { int data; struct BitTree* LChild; //左子树 struct BitTree* RChild; //右子树 }bittree; //创建二叉树 bittree* createBitTree(bittree* BT) { int num = 0; scanf("%d", &num); if (num != -1) { //输入-1代表结束 BT = (bittree*)malloc(sizeof(bittree)); BT->data = num; printf("输入%d的左结点值:", BT->data); BT->LChild = createBitTree(BT->LChild); printf("输入%d的右结点值:", BT->data); BT->RChild = createBitTree(BT->RChild); } else { BT = NULL; //输入-1,结点为NULL } return BT; } //先序遍历 void PrePrint(bittree* BT) { if (BT != NULL) { printf("%d ", BT->data); PrePrint(BT->LChild); PrePrint(BT->RChild); } else { //结点为NULL,返回上一层 return; } } //方式一 /* int flag = 0; //定义一个全局变量来判断是否查找到了值 void PrintAncestors(bittree* BT, int x) { if (!BT) return; if (BT->data == x) { flag = 1; //查询到值的时候 改变标志位 return; } if (flag == 0) { PrintAncestors(BT->LChild, x); //若没有查找到往节点的左侧查找 } if (flag == 0) PrintAncestors(BT->RChild, x);//若没有查找到往节点的右侧查找 if (flag == 1) { printf("%d ", BT->data); } } */ //方式二 int PrintAncestors(bittree* BT, char x) { if (!BT) return 0; if (BT->data == x) { return 1; } //这个可以这样理解 //如果一颗二叉树他的左孩子有要查询的结点或者他的右孩子里面有要查询的结点那么该节点就是祖先结点 if (PrintAncestors(BT->LChild, x) || PrintAncestors(BT->RChild, x)) { printf("%d ", BT->data); return 1; } else { return 0; } } void main() { int num = 0; bittree* myBT = NULL; myBT = createBitTree(myBT); printf("先序遍历二叉树:\n"); PrePrint(myBT); printf("\n"); printf("请输入你要查找的值:"); scanf("%d", &num); //printf("开始寻找%d的所有祖先:\n", num); printf("%d的所有祖先是:\n", num); PrintAncestors(myBT, num); }
参考自:https://blog.csdn.net/qq_41934478/article/details/98121209