• 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;
    }
  • 相关阅读:
    MongoDB环境配置
    Python之路【第二十七篇】:反射
    Socket网络通讯,TCP三次握手和四次释放,与UDP的差别
    iOS 常用第三方
    UISegmentedControl的使用
    OC取应用程序目录的路径
    KVC中setValuesForKeysWithDictionary
    KVC和KVO的简单对比
    C语言 内存和地址
    html基础知识
  • 原文地址:https://www.cnblogs.com/gaojs/p/14947766.html
Copyright © 2020-2023  润新知