查找二叉树(tree_a)(信息学奥赛一本通- P1367)
·
【题目描述】
已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为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 <bits/stdc++.h>
using namespace std;
int n,x;
int id=1;//查找的数的中序输出节点编号
struct node{
int l;
int r;
int data;
}tre[200];
void inorder(int root){
if(tre[root].l) inorder(tre[root].l);
if(tre[root].data!=x) id++;
else cout<<id;
if(tre[root].r) inorder(tre[root].r);
}
int main(){
cin>>n>>x;
for(int i=1;i<=n;i++)
cin>>tre[i].data>>tre[i].l>>tre[i].r;
inorder(1);
return 0;
}
更多推荐
所有评论(0)