1115. Counting Nodes in a BST (30)
Posted 给杰瑞一块奶酪~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 28Sample 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); }
以上是关于1115. Counting Nodes in a BST (30)的主要内容,如果未能解决你的问题,请参考以下文章
PAT 1115 Counting Nodes in a BST
[二叉查找树] 1115. Counting Nodes in a BST (30)