1367:查找二叉樹(tree_a)

【題目描述】

已知一棵二叉樹用鄰接表結構存儲,中序查找二叉樹中值爲x的結點,並指出是第幾個結點。例:如圖二叉樹的數據文件的數據格式如下:

【輸入】

第一行n爲二叉樹的結點個樹,n≤100;第二行x表示要查找的結點的值;以下第一列數據是各結點的值,第二列數據是左兒子結點編號,第三列數據是右兒子結點編號。

【輸出】

一個數即查找的結點編號。

【輸入樣例】

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

【輸出樣例】

4
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
#include <set>
#include <queue>
#include <stack>
#define sf(a) scanf("%d\n",&a)
#define pf(a) printf("%.2lf\n",a)
#define pi acos(-1.0)
#define E 1e-8
#define ms(a) memset(a,0,sizeof a)
#define min_ms(a) memset(a,-1,sizeof a)
#define max_ms(a) memset(a,0x3f3f3f3f,sizeof a)
#define rep(a,b,c) for(int a=b;a<=c;a++)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef struct node;
typedef node *tree;
const int inf=0x3f3f3f3f;
const int idata=100+5;
const int mod=1e9+7;

int i,j,k;
int judge,flag,root;
int n,m,t,tag;
int maxx=0,minn=inf;
int cnt,len,sum,ans;
priority_queue<ll, vector<ll>,less<ll> >q;
int a[idata];
int step[idata][idata];
string s;

struct node
{
    int data;
    int l,r;
}node[idata];

void bt_find(int point,int tag)
{
    if(node[point].l)
    {
        bt_find(node[point].l,tag);
    }
    ans++;
    if(node[point].data==tag)
    {
        cout<<ans<<endl;
        return;
    }
    if(node[point].r)
    {
        bt_find(node[point].r,tag);
    }
}
signed main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    while(cin>>n>>tag)
    {
        for(i=1;i<=n;i++)
        {
            cin>>node[i].data>>node[i].l>>node[i].r;
        }
        bt_find(1,tag);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章