zoukankan      html  css  js  c++  java
  • PAT(Advanced Level)A1115. Counting Nodes in a BST

    题意

    根据要求插入节点到BST里面,最后要输出最低的两层的结点树木

    思路

    • 先按照BST来建树,建树之后用dfs来统计每一层的结点数,同时要用一个变量来记住最大深度,那么我们就可以得到最低两层的结点数量了

    代码

    #include <iostream>
    #include <vector>
    #include <queue>
    #include <map>
    #include <string.h>
    #include <set>
    #include <unordered_map>
    #include <algorithm>
    using namespace std;
    int cnt[1010] = {0};
    int max_depth = -1;
    struct node {
        int val;
        struct node* left;
        struct node* right;
        node(int x): val(x), left(NULL), right(NULL) {}
    };
    void insert(node*& root, int x) {
        if(root == NULL) {
            root = new node(x);
            return;
        }
        if(x > root->val)
            insert(root->right, x);
        else
            insert(root->left, x);
        return;
    }
    void dfs(node* root, int depth) {
        if(root) {
            cnt[depth]++;
            max_depth = max(max_depth, depth);
            dfs(root->left, depth + 1);
            dfs(root->right, depth + 1);
        }
    }
    int main() {
        int N, t;
        cin >> N;
        node* root = NULL;
        while(N--) {
            cin >> t;
            insert(root, t);
        }
        dfs(root, 0);
        int sum = cnt[max_depth - 1] + cnt[max_depth];
        cout << cnt[max_depth] << " + " << cnt[max_depth - 1] << " = " << sum;
        return 0;
    }
    
    如有转载,请注明出处QAQ
  • 相关阅读:
    2013-3 阿里性能稳定性沙龙
    8种Nosql数据库系统对比
    百度技术笔记之2013-1
    百度技术沙龙之2013-2&3
    【消息队列MQ】各类MQ比较
    Unity3D 游戏引擎之C#使用Socket与HTTP连接server数据传输包
    android的ndk学习(1)
    杭电 3555 Bomb
    FaceBook开源库Fresco
    SDUTOJ 2476Period
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/14533011.html
Copyright © 2011-2022 走看看