//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;
}
【二叉树】查找结点(先序+层次)
最新推荐文章于 2022-02-04 16:04:57 发布
本文介绍了一种在二叉树中查找特定节点的算法,包括层次遍历和先序遍历两种方法。通过实例演示了如何使用C++实现这些算法,并展示了如何获取节点在树中的位置。
364

被折叠的 条评论
为什么被折叠?



