查找二叉树(树)

Description

已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为x的结点,并指出是第几个结点

Input

第一行为二叉树的结点个数,n<=100;第二行x表示要查找的结点的值;以下第一列数值是各结点的值,第二列数据是左儿子结点编号,第二列数是右儿子结点编号

Output

输出一个数即查找的结点编号

Sample Input

 

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


解题思路:先根据读入数据构建一个二叉树,然后边寻找边进行统计,最后输出统计出的那个值即可。


程序:
type
  tree=^node;
  node=record
         data:longint;
         lchild,rchild:tree;
  end;

const
  maxn=100;

var
  n,i,k,ans:longint;
  a:array[1..maxn,1..3] of longint;
  bt:tree;

procedure build(var bt:tree;x:longint);
  begin
    if x=0 then
      begin
        bt:=nil;
        exit;
      end;
    new(bt);
    bt^.data:=a[x,1];
    build(bt^.lchild,a[x,2]);
    build(bt^.rchild,a[x,3]);
end;

procedure print(bt:tree);
  begin
    if bt=nil then exit;
    print(bt^.lchild);
    inc(ans);
    if bt^.data=k then
      begin
        writeln(ans);
        halt;
      end;
    print(bt^.rchild);
end;

begin
  readln(n);
  readln(k);
  for i:=1 to n do
    readln(a[i,1],a[i,2],a[i,3]);
  build(bt,1);
  print(bt);
end.


版权属于: Chris
原文地址: http://blog.sina.com.cn/s/blog_83ac6af80102v0mu.html
转载时必须以链接形式注明原始出处及本声明。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值