zoukankan      html  css  js  c++  java
  • PAT Advanced 1115 Counting Nodes in a BST (30分)

    A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

    • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • Both the left and right subtrees must also be binary search trees.

    Insert a sequence of numbers into an initially empty binary search tree. Then you are supposed to count the total number of nodes in the lowest 2 levels of the resulting tree.

    Input Specification:

    Each input file contains one test case. For each case, the first line gives a positive integer N (≤) which is the size of the input sequence. Then given in the next line are the N integers in [ which are supposed to be inserted into an initially empty binary search tree.

    Output Specification:

    For each case, print in one line the numbers of nodes in the lowest 2 levels of the resulting tree in the format:

    n1 + n2 = n
    
     

    where n1 is the number of nodes in the lowest level, n2 is that of the level above, and n is the sum.

    Sample Input:

    9
    25 30 42 16 20 20 35 -5 28
    
     

    Sample Output:

    2 + 4 = 6

    已知N个数,插入二叉搜索树后,进行输出最后两层一共有多少个节点。

    #include <iostream>
    using namespace std;
    struct node {
        int val, level;
        node *left = NULL, *right = NULL;
        node(int val):val(val){}
    };
    node *root = NULL;
    int max_level = 0, a = 0, b = 0;
    /** 插入节点 */
    node* Insert(node *n, int val) {
        if(n == NULL) return new node(val);
        else if(n->val < val) n->right = Insert(n->right, val);
        else n->left = Insert(n->left, val);
        return n;
    }
    /** 标注层级 */
    void dfs(node *n, int level) {
        if(n != NULL) {
            n->level = level;
            max_level = max(max_level, level);
            dfs(n->left, level + 1);
            dfs(n->right, level + 1);
        }
    }
    /** 计算最后两层 */
    void dfs_count(node *n) {
        if(n != NULL) {
            if(n->level == max_level) a++;
            if(n->level == max_level - 1) b++;
            dfs_count(n->left);
            dfs_count(n->right);
        }
    }
    int main() {
        int N, tmp;
        scanf("%d", &N);
        for(int i = 0; i < N; i++){
            scanf("%d", &tmp);
            root = Insert(root, tmp);
        }
        dfs(root, 0);
        dfs_count(root);
        printf("%d + %d = %d", a, b, a + b);
        system("pause");
        return 0;
    }
  • 相关阅读:
    NHibernate初学者指南系列文章导航
    c# 类一般在哪里实例化,是在类内、方法内还是其他地方?
    日期和时间的正则表达式
    virtual和abstract区别
    VS2010和选中代码相同的代码的颜色设置,修改高亮颜色
    SqlServer表和EXCEL数据互相复制方法
    C#操作XML的方法
    1、Spring Boot 2.x 简介
    C语言学习系列(六)基本语法
    C语言学习系列(六)存储类
  • 原文地址:https://www.cnblogs.com/littlepage/p/12249317.html
Copyright © 2011-2022 走看看