题目内容
具体题目见连接:https://www.patest.cn/contests/pat-a-practise/1115
题目分析
1.看到这个树首先要明白与之前的一道题1099的区别。1099是说建立一个二叉搜索树,把每个节点的左右孩子都已经给出。根据给出的节点建立二叉搜索树,建立之后把给定的一串数字插进去。但是1115是说从一个空的二叉排序树,一个一个节点插进去,肯定不一样啊。建树方式不一样。因此,1099用中序遍历建树,而1115用递归建立。所以,1099是把数组序列填进建立好的树中,而1115是手动建立二叉树。
2.建立树,首先一个树节点的结构体,用到指针,左右孩子都是指针。
3.层次遍历,记下每一层的节点就行了,用vector二重就行。
代码如下
#include <iostream>
#include <algorithm>
#include <queue>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
struct BiNode{//建立二叉树,用指针
int data;
BiNode* left;
BiNode* right;
};
void insert(BiNode* &root,int data){//插入二叉排序树
if(root==NULL){
root = new BiNode();
root->data = data;
root->left = NULL;
root->right = NULL;
}
else{
if(data<=root->data){
insert(root->left,data);
}else{
insert(root->right,data);
}
}
}
void preOrder(BiNode* &root){//前序遍历
if(root->left!=NULL)
preOrder(root->left);
cout<<root->data<<" ";
if(root->right!=NULL)
preOrder(root->right);
}
int main(int argc, char *argv[]) {
int n;
cin>>n;
BiNode* root = NULL;
for(int i=0;i<n;i++){
int t;
cin>>t;
insert(root,t);
}
queue<BiNode*> q;
q.push(root);
preOrder(root);
vector< vector<int> > v(1001);
int index = 0;
while(!q.empty()){
int size = q.size();
for(int i=0;i<size;i++){
BiNode* top = q.front();
q.pop();
v[index].push_back(top->data);
if(top->left!=NULL){
q.push(top->left);
}
if(top->right!=NULL){
q.push(top->right);
}
}
index++;
}
//输出
int n1 = v[index-1].size();
int n2 = v[index-2].size();
cout<<n1<<" + "<<n2<<" = "<<n1+n2<<endl;
//for(int i=0;i<index;i++){
// for(int j=0;j<v[i].size();j++){
// cout<<v[i][j]<<" ";
// }
// cout<<endl;
// }
return 0;
}