1367:查找二叉树(tree_a)
时间限制: 1000 ms 内存限制: 65536 KB
【题目描述】
已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为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
1. #include <iostream> 2. #include <cstdio> 3. #include <cstring> 4. #include <algorithm> 5. using namespace std; 6. struct node{ 7. int data; 8. int left,right; 9. }tree[110]; 10. int n,t,ans; 11. void inorder(int root){ 12. if(tree[root].left!=0) inorder(tree[root].left); 13. ans++; 14. if(tree[root].data==t){ 15. cout<<ans<<endl;return; 16. } 17. if(tree[root].right!=0) inorder(tree[root].right); 18. } 19. int main() 20. { 21. cin>>n>>t; 22. for(int i=1;i<=n;i++) cin>>tree[i].data>>tree[i].left>>tree[i].right; 23. inorder(1); 24. return 0; 25. }