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;
}

 

上一篇:【LeetCode每天一题】 Unique Binary Search Trees(唯一二叉搜索树)


下一篇:解决Android Studio无法下载sdk的问题