【二叉树】查找结点(先序+层次)

本文介绍了一种在二叉树中查找特定节点的算法,包括层次遍历和先序遍历两种方法。通过实例演示了如何使用C++实现这些算法,并展示了如何获取节点在树中的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//ABC##DE#G##F### 
#include <iostream>
using namespace std;

typedef struct node
{
	char data;
	struct node *lchild;
	struct node *rchild;
	int step; 
}BTnode;

void Create(BTnode *&T)
{
	char ch;
	cin>>ch;
	if(ch == '#')
	{
		T = NULL;
	}
	else
	{
		T = new BTnode;
		T->data = ch;
		Create(T->lchild);
		Create(T->rchild);
	}
}

int Level_Find(BTnode *T, char x)		//层次遍历查找结点 
{
	if(T == NULL) return 0;
	BTnode *a[100];
	int front = -1, rear = 0;
	a[0] = T, a[0]->step = 1;
	while(front != rear)
	{
		front++;
		if(a[front]->data == x) return a[front]->step;
		if(a[front]->lchild) a[++rear] = a[front]->lchild, a[rear]->step = a[front]->step + 1;	//step为结点的高度 
		if(a[front]->rchild) a[++rear] = a[front]->rchild, a[rear]->step = a[front]->step + 1;
	}
	return 0;
}

int Pre_Find(BTnode *T, char x, int h)	//	先序遍历查找结点 
{
	int l;
	if(!T) return 0;		//空树,返回0 
	if(T->data == x) return h;	//查找到,返回当前高度 
	l = Pre_Find(T->lchild, x, h+1);	//在左子树中查找 
	if(l != 0) return l;		//左子树查找到了,返回该值 
	return Pre_Find(T->rchild, x, h+1);	//左子树没查找到,返回查找右子树的值 
}

int main()
{
	BTnode *T, *t;
	Create(T);
	cout<<Level_Find(T, 'F')<<endl;
	cout<<endl;
	int loc = Pre_Find(T,'Q',1);
	if(loc)
	cout<<loc<<endl;
	else
	cout<<"No Find"<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值