1115. Counting Nodes in a BST (30)

4 篇文章 0 订阅

题目详情:https://www.patest.cn/contests/pat-a-practise/1115

感觉很简单,但是没有写temp->left=NULLtemp->right=NULL 导致程序写错了,想了好长时间!特此纪念!

#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;
typedef struct BSTree
{
    struct BSTree* left;
    int data,level;//level存储该节点所在的层次
    struct BSTree* right;
}BSTree;
BSTree* insert(BSTree* root,int value)
{
    if(root==NULL)//找到插入位置
    {
        BSTree* temp=(BSTree*)malloc(sizeof(BSTree));
        temp->left=NULL;temp->right=NULL; //没写这两句话居然错了
        temp->data=value;
        return temp;
    }
    else if( root->data >= value )//根节点的值较大,则需要到左子树上去找插入位置
    {
        root->left=insert(root->left,value);
    }
    else//root->data < value,去右子树上找插入位置
    {
        root->right=insert(root->right,value);
    }
    return root;
}

vector<int> levelOrder(BSTree* root)
{
    vector<int> num_level;//存储每层节点的个数
    vector<BSTree*> queue;//存储树节点的队列
    BSTree* temp;
    root->level=1;//根节点的层次设置为1
    int front=0;//队列中未访问的第一个节点
    queue.push_back(root);
    while( front!=queue.size() )
    {
        temp=queue[front];
        if(temp->left)
        {
            temp->left->level=temp->level+1; //层次加1
            queue.push_back(temp->left);//把左节点加入到队列中
        }
        if(temp->right)
        {
            temp->right->level=temp->level+1;//层次加1
            queue.push_back(temp->right);//把右节点加入到队列中
        }
        if(num_level.size()>=temp->level)//temp节点所在的节点层次已经在num_level中
            num_level[temp->level -1]++;//那么直接将层次的节点个数加1
        else//否则把1添加到最后,代表该层次中只有一个节点
            num_level.push_back(1);
        front++;
    }
    return num_level;
}
int main()
{
    int n,temp;
    BSTree* root=NULL;
    scanf("%d",&n);
    for( int i=0;i<n;++i )
    {
        scanf("%d",&temp);
        root=insert(root,temp);
    }
    vector<int> num_level=levelOrder(root);//可能只有一层节点,测试用例没有这种可能
    int length=num_level.size();
    cout<<num_level[length-1]<<" + "<<num_level[length-2]<<" = "<<num_level[length-1]+num_level[length-2]<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值