pat 1115----指针建树,层次遍历

本文详细解析PAT-A 1115题目的解题思路,通过对比1099题,强调了两题在二叉树构建上的不同。介绍了如何根据给定数字序列构建二叉搜索树,并实现层次遍历,最终计算特定层级节点数量之和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目内容
具体题目见连接: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值