• 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 (<=1000) which is the size of the input sequence. Then given in the next line are the N integers in [-1000 1000] 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
    
    建树,然后不断更新最大深度和次大深度,及相应点个数。
    代码:
    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <map>
    using namespace std;
    struct tree
    {
        int data;
        tree *left,*right;
        tree()
        {
            data = 0;
            left = right = NULL;
        }
    }*head;
    int n;
    int m,c1,c2;
    tree *insert_(tree *r,int d,int h)
    {
        if(r == NULL)
        {
            r = new tree();
            r -> data = d;
            if(h > m)
            {
                m = h;
                c2 = c1;
                c1 = 1;
            }
            else if(h == m)c1 ++;
            else if(h == m - 1)c2 ++;
        }
        else if(d > r -> data)
        {
            r -> right = insert_(r -> right,d,h + 1);
        }
        else
        {
            r -> left = insert_(r -> left,d,h + 1);
        }
        return r;
    }
    int main()
    {
        int d;
        scanf("%d",&n);
        head = NULL;
        for(int i = 0;i < n;i ++)
        {
            scanf("%d",&d);
            head = insert_(head,d,1);
        }
        printf("%d + %d = %d",c1,c2,c1 + c2);
    }
    View Code

  • 相关阅读:
    IDEA开发 Scala 项目
    mvn编译时绕过本地jar去maven仓库下载问题
    三角化(转载)
    分布式文件服务器介绍(转载)
    VSCode 设置侧边栏字体大小
    libLas编译
    OSG编译
    vcpkg.exe安装与应用
    OpenCASCADE编译
    gl2ps编译
  • 原文地址:https://www.cnblogs.com/8023spz/p/8994706.html
Copyright © 2020-2023  润新知