1367:查找二叉树(tree_a)

简介: 1367:查找二叉树(tree_a)

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


相关文章
|
1月前
|
缓存 索引
图解B Tree和B+ Tree
图解B Tree和B+ Tree
35 0
|
8月前
|
Python
二叉搜索树(Binary Search Tree
二叉搜索树(Binary Search Tree,简称 BST)是一种特殊的二叉树结构,它的每个节点具有以下性质:
59 4
|
6天前
|
数据库 C++
二叉搜索树(Binary Search Tree,BST)
二叉搜索树(Binary Search Tree,BST)
|
6天前
|
存储 算法 编译器
|
1月前
|
定位技术 索引
R-tree 总结
R-tree 总结
15 0
|
1月前
|
存储 算法 Python
赢者树(Losers Tree)
赢者树(Losers Tree)是一种经典的数据结构,常用于外部排序(External Sorting)算法中,将多个有序的子序列合并成一个有序的序列。赢者树本质上是一棵完全二叉树,每个节点存储着一个子序列的最小值。每次合并操作时,比较各个子序列的最小值,选出最小值并将其存入输出序列中,同时将该最小值所在的节点从赢者树中删除,并将其对应的子序列的下一个元素作为新的最小值插入到赢者树中进行调整,直到所有子序列的元素都被合并完成。
42 3
|
7月前
树(Tree)和二叉树(Binary Tree)——(代码篇)
树(Tree)和二叉树(Binary Tree)——(代码篇)
51 0
|
11月前
|
存储 数据库 索引
B-Tree和B+Tree特点
B - Tree和B + Tree特点
79 0
|
数据库 索引
B-Tree, B+Tree
B-Tree, B+Tree
60 0
1127. ZigZagging on a Tree (30)
#include #include #include using namespace std; int n; const int maxn = 31; struct node { int data; node *l,...
1161 0