• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山不在高,有金则名!
博客园    首页    新随笔    联系   管理    订阅  订阅

1367:查找二叉树(tree_a)

已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为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;

struct Node {
    int value;
    int left, right;
    int dad; // 父亲
};

bool FindRoot(const vector<Node> &a)
{
    for (int i = 1; i < a.size(); i++) {
        if (a[i].dad == 0 && a[i].value > 0) {
            return i;
        }
    }
    return 0;
}

bool FindValue(const vector<Node> &a, int i, int x, int &cnt)
{
    if (i <= 0 || i >= a.size()) {
        return false; // 越界
    } else {
        if (FindValue(a, a[i].left, x, cnt)) {
            return true; // 找到
        }
        cnt += 1; // 查找过1个元素 // 中序
        // cout << i << ":" << cnt << endl;
        if (a[i].value == x) {
            return true; // 找到
        }
        if (FindValue(a, a[i].right, x, cnt)) {
            return true; // 找到
        }
        return false; // 没找到
    }
}


int main()
{
    // freopen("1.txt", "r", stdin);
    int n, x;
    cin >> n >> x;
    vector<Node> a(n + 1);
    for (int i = 1; i < n; i++) {
        cin >> a[i].value;
        cin >> a[i].left;
        cin >> a[i].right;
        a[a[i].left].dad = i;
        a[a[i].right].dad = i;
    }
    int root = FindRoot(a);
    int cnt = 0;
    FindValue(a, root, x, cnt);
    cout << cnt;
    return 0;
}

 

posted @ 2021-06-28 22:26  杭州山不高  阅读(219)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3