PAT A1115 Counting Nodes in a BST (30 分)——二叉搜索树,层序遍历或者dfs

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:

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 <stdio.h>
#include <algorithm>
#include <set>
#include <vector>
#include <queue>
using namespace std;
int height;
struct node{
int data,h,lvl;
node* l,*r;
};
node* newnode(int x){
node* root = new node;
root->data=x;
root->l=NULL;
root->r=NULL;
root->h=;
return root;
}
int geth(node* root){
if(root==NULL) return ;
return root->h;
}
void updateh(node* root){
root->h = max(geth(root->l),geth(root->r))+;
}
void insert(node* &root,int x){
if(root==NULL) {
root=newnode(x);
return;
}
if(x>root->data){
insert(root->r,x);
updateh(root);
}
else if(x<=root->data){
insert(root->l,x);
updateh(root);
}
}
int main(){
int n;
scanf("%d",&n);
node* root = NULL;
for(int i=;i<n;i++){
int x;
scanf("%d",&x);
insert(root,x);
}
height=root->h;
int n1=,n2=;
queue<node*> q;
root->lvl=;
q.push(root);
while(!q.empty()){
node* now=q.front();
q.pop();
//printf("%d %d\n",now->data,now->lvl);
if(now->l!=NULL){
now->l->lvl=now->lvl+;
q.push(now->l);
}
if(now->r!=NULL){
now->r->lvl=now->lvl+;
q.push(now->r);
}
if(now->lvl==height)n1++;
if(now->lvl==height-)n2++;
}
printf("%d + %d = %d",n1,n2,n1+n2);
}

注意点:二叉搜索树的建立与层序遍历。不过好像做麻烦了,用dfs会更简洁。又好像dfs都不用,可以直接在插入时候加个lvl数组算

上一篇:PAT 甲级 1115 Counting Nodes in a BST


下一篇:[LeetCode&Python] Problem 783. Minimum Distance Between BST Nodes