查找二叉树

Problem Description

已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为x的结点,并指出是第几个结点。

Input

输入有多组数据,每组数据的第一行n为二叉树的结点个数,n<=100;第2行x表示要查找的结点的值;以下n列数据中每列第1个数是结点的值,第2个数是左孩子的编号,第3个数是右孩子的编号。

Output

对于每组数据输出一个数即查找的结点编号。

Sample Input

7
15
5 2 3
12 4 5
10 0 0
29 0 0
15 6 7
8 0 0
23 0 0

Sample Output

4
#include <iostream>
#include <cstring>
using namespace std;
typedef struct node{
    int v,l,r;
}node;
node tr[110];
int ans;
bool MFS(int r,int x){
    if(tr[r].l!=0)
        if(MFS(tr[r].l,x))
            return true;
    ans++;
    if(tr[r].v==x)
        return true;
    if(tr[r].r!=0)
        if(MFS(tr[r].r,x))
            return true;
    return false;
}
int main(){
    int n,x;
    while(cin>>n){
        cin>>x;
        memset(tr,0,sizeof(tr));
        for(int i=1;i<=n;i++)
            cin>>tr[i].v>>tr[i].l>>tr[i].r;
        ans=0;
        if(MFS(1,x)){
            cout<<ans<<endl;
        }else{
            cout<<0<<endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值