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:
10
25 30 42 16 20 20 35 -5 28 22
Sample Output:
3 + 4 = 7
解题思路:首先注意定义,二叉搜索树的定义,不同于其他的二叉搜索树的题就是左子树是小于等于根节点的,其次使用递归进行建树和遍历操作,得到最深的层数和每一层的节点数,最后输出最后两层的节点个数和节点总数
以下是代码:
insert操作
//将无用的节点置成0
//节点从0开始
void insert(int &u , int x)
{
if(!u)
{
u = idx ++;
v[u].val = x;
}
else if(x <= v[u].val) insert(v[u].left , x);
else insert(v[u].right , x);
}
或者将所有节点置成-1使用memset函数
dfs
int max_depth = 0;
int cnt[N] = {0};
void dfs(int u , int depth)
{
if(!u) return ;
cnt[depth] ++;
max_depth = max(max_depth , depth);
dfs(v[u].left , depth + 1);
dfs(v[u].right , depth + 1);
}
完整代码:
//注意该题不同于其他二叉搜索树的是左子树是
//小于等于根的 而不是 小于
#include<iostream>
using namespace std;
const int N = 1010;
struct Node
{
int left;
int right;
int val;
}v[N];
int n;
int idx = 1;
//将无用的节点置成0
void insert(int &u , int x)
{
if(!u)
{
u = idx ++;
v[u].val = x;
}
else if(x <= v[u].val) insert(v[u].left , x);
else insert(v[u].right , x);
}
int max_depth = 0;
int cnt[N] = {0};
void dfs(int u , int depth)
{
if(!u) return ;
cnt[depth] ++;
max_depth = max(max_depth , depth);
dfs(v[u].left , depth + 1);
dfs(v[u].right , depth + 1);
}
int main()
{
cin>>n;
int root = 0;
for(int i = 0;i < n;i ++)
{
int num;
cin>>num;
insert(root , num);
}
dfs(root , 0);
printf("%d + %d = %d" , cnt[max_depth] , cnt[max_depth - 1] , cnt[max_depth] + cnt[max_depth - 1]);
return 0;
}