[Postgraduate Entrance Examination Data Structure Code Question 5] Binary tree search for specified keywords and their parent nodes

Question: It is known that a binary tree already exists. The node of the binary tree has three fields, namely the left and right child pointer fields and the data field. The data field is of character type, and the pointer bt is specified to point to the root node. Given a character ch, please write a program to find whether there is a node with data domain ch in the binary tree? If it exists, find the parent node of the node.

Difficulty: ★★★

#include<stdio.h>
#include<stdlib.h>
//二叉树存储结构
typedef struct node{
	char key;//数据域
	struct node *left,*right;//左右孩子指针域 
}BiNode;
//递归查找指定关键字结点
void find(BiNode *T,char target,BiNode *parent){
	if(T){
		int left_s,right_s;
		//如果当前结点就是要找的关键字结点,则输出其父节点关键字
		if(T->key==target){
			if(!parent)printf("NULL");
			else printf("%c",parent->key);
		}
		//递归搜索 
		if(T->left)  find(T->left,target,T);
		if(T->right) find(T->right,target,T);
	}
} 

int main(){
	char target;//目标关键字符
	scanf("%c",&target);
	find(bt,target,NULL);//bt为题目已知条件,指向该树的根节点
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_52487066/article/details/134403603