PAT 1115 Counting Nodes in a BST

二叉搜索树(左子树的元素 < = <= <=父节点 < < <右节点),求最下面两层的节点个数,以及其总和。
这一题建立二叉搜索树,建立时记下层数,求出最大层数,然后遍历整个树,寻找等于最大层和第二层的节点,记下个数。
建立树的时候才发现,自己对指针的理解还不够,出了一些错误。这一题难度不大,算是考基础的一题,自己没有马上写出来,也是对建立树的过程还没掌握,在解题中还老想着寻找什么快速的方法,还是要把基础打好。现在想想,程序还是要码过代码才能知道是不是真的会了。
(用时:57:38.45)

#include <bits/stdc++.h>
using namespace std;
struct BiNode {
    BiNode *left,*right;
    int value;
    int high;
};
int maxHigh = 0;
int lowest[2] = {0};
BiNode*  createTree(BiNode *root,int node[],int length)
{
    root = (BiNode *)malloc(sizeof(BiNode));
    root->left = NULL;
    root->right = NULL;
    root->value = node[0];
    root->high = 1;

    int high = 1;
    bool isleft = true;
    maxHigh = 1;
    for(int i=1; i<length; i++) {
        BiNode *p = root;
        high = 1;
        isleft = true;
        while(p) {
            if( node[i] >p->value) {
                if(p->right) {
                    p=p->right;
                } else {
                    isleft =false;
                    break;
                }
            } else {
                if(p->left) {
                    p=p->left;
                } else {

                    break;
                }
            }

        }
        BiNode *t = (BiNode *)malloc(sizeof(BiNode));

        t->left = NULL;
        t->right = NULL;
        t->value = node[i];
        t->high = p->high + 1;
        if(isleft) {
            p->left = t;
        } else {
            p->right = t;
        }
        if(maxHigh <t->high ) {
            maxHigh = t->high ;
        }
    }
    return root;
}

void PreOrder(BiNode *root)
{
    if(root == NULL) {
        return;
    }
    if(root->high == maxHigh) {
        lowest[0]++;
    } else if(root->high == maxHigh-1) {
        lowest[1]++;
    }

    PreOrder(root->left);
    PreOrder(root->right);
}

int main()
{
    int n;
    scanf("%d",&n);
    int node[n];
    for(int i=0; i<n; i++) {
        scanf("%d",&node[i]);
    }

    BiNode *root;

    root = createTree(root,node,n);

    PreOrder(root);
    printf("%d + %d = %d\n",lowest[0],lowest[1],lowest[0] + lowest[1]);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值