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 [−10001000] 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:
1
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:
1 2
9 25 30 42 16 20 20 35 -5 28
Sample Output:
1
2 + 4 = 6
题解
思路
建立二叉搜索树,按照给定的顺序。
就是从根部开始找,小的往左走,大的往右走,找到空位插进去,很直观
层次遍历,找到最深的两层即可。
不难。
数据结构
Node 是一个类,包含三个属性
值
左孩子
右孩子
root 是树根
ans 存放所有的层数的出现次数。比如[1,1,3,3,4,5]代表第一层出现了2次,第3层出现了2次,第四层出现了一次。
intinsert(Node *node, int j){ if (j > node->val) { if (!node->right) node->right = new Node(j); else insert(node->right, j); } else { if (!node->left) node->left = new Node(j); else insert(node->left, j); } }
vector<int> ans;
intlevel(Node *node, int lev){ ans.push_back(lev); if (node->left) level(node->left, lev + 1); if (node->right) level(node->right, lev + 1); }
intmain(){ int n; cin >> n; int nums[n]; for (int i = 0; i < n; i++) cin>>nums[i];
Node *root = new Node(nums[0]); for (int i= 1;i<n;i++) insert(root, nums[i]);
level(root, 0); int max_level = 0; for (auto it:ans) max_level = max(max_level,it); int a = 0; int b = 0; for (auto it:ans){ if (it == max_level) a += 1; elseif (it == max_level - 1) b += 1; } printf("%d + %d = %d\n" ,a, b, a + b); }