PATA1115题解

本文介绍了一种利用前序遍历构建二叉查找树的方法,并通过层序遍历来统计每层节点的数量,最终输出树最后两层的节点总数。该方法适用于算法竞赛及数据结构的学习。

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

通过前序遍历构造二叉查找树,再通过树的层序遍历保存每一层的节点数,最后输出最后两层的节点数即可

//
//  main.cpp
//  PATA1115
//
//  Created by Phoenix on 2018/2/24.
//  Copyright © 2018年 Phoenix. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
int n, num[1010];
struct Node {
    int data;
    Node *lchild, *rchild;
};

Node* newnode(int x) {
    Node* root = new Node;
    root->data = x;
    root->lchild = root->rchild = NULL;
    return root;
}

void insert(Node* &root, int x){
    if (root == NULL) {
        root = newnode(x);
        return;
    }
    if(x <= root->data) insert(root->lchild, x);
    else insert(root->rchild, x);
}

void create(Node* &root, int a[]){
    for(int i = 0; i < n; i++) {
        insert(root, a[i]);
    }
}

vector<int> v;
void levelorder(Node* root) {
    queue<Node*> q;
    q.push(root);
    Node *lastnode = root, *newlastnode = NULL;
    int num = 0;
    while(!q.empty()) {
        Node* top = q.front();
        q.pop();
        num++;
        if(top->lchild) {
            q.push(top->lchild);
            newlastnode = top->lchild;
        }
        if(top->rchild) {
            q.push(top->rchild);
            newlastnode = top->rchild;
        }
        if(top == lastnode) {
            v.push_back(num);
            lastnode = newlastnode;
            num = 0;
        }
    }
}

int main(int argc, const char * argv[]) {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d", &num[i]);
    }
    Node* root = NULL;
    create(root, num);
    levelorder(root);
    int i = v.size();
    int a = v[i - 1], b = v[i - 2];
    printf("%d + %d = %d\n", a, b, a + b);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值