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

  • 相关阅读:
    java常用英文解释
    干货——myeclipse快捷键
    上海面试经常遇到的事务安全问题
    2016java技术岗面试题
    Echarts 获取后台数据 使用后台数据展示 柱形图
    JS实现的MAP结构数据
    Spring MVC 返回json数据 报406错误 问题解决方案
    junit 注意事项,切记
    JNDI中 java:comp/env 的理解
    JMS发布/订阅消息传送例子
  • 原文地址:https://www.cnblogs.com/8023spz/p/8994706.html
Copyright © 2011-2022 走看看