zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ABS(引数と同じ大きさの正の数を返す)
    WRITE
    LEAVE TO LIST-PROCESSING
    SHIFT(文字列の指定位置数の移動)
    【EXCEL】SUMIF(条件を指定して数値を合計する)
    【EXCEL】SUMIFS(複数の条件を指定して数値を合計する)
    【財務会計】流動資産と固定資産の違いとは?ディズニーを例にわかりやすく解説
    【財務会計】償却 とは
    【財務会計】固定資産の除却と廃棄の違い
    尽力去做你力所能及的事
  • 原文地址:https://www.cnblogs.com/8023spz/p/8994706.html
Copyright © 2011-2022 走看看