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;
}