[NOIp]二叉树的指针实现

本文介绍了如何使用malloc分配内存来创建二叉树节点,并通过一个具体的C++示例展示了二叉树的构建过程。此外,还分享了一个实用的小技巧:通过typedef简化类型定义。

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

今天学到了二叉树,一开始被那个malloc弄的很迷,后来发现root=(BiTreeNode*)malloc(sizeof(BiTreeNode))的那个星号是在后面的,吐血。。

代码里面有个小技巧,就是typedef struct XXX{...}XXX,这样就使用XXX代替了struct XXX,可以少打一些字了233.

#include<bits/stdc++.h>
using namespace std;

typedef struct BiTreeNode {
    int data;
    BiTreeNode* left;
    BiTreeNode* right;
    void operator =(BiTreeNode* b) {
        data=b->data;
        left=b->left;
        right=b->right;
    };
} BiTreeNode;

BiTreeNode *root;

void Create(BiTreeNode* root,int data) { //add a node to the tree
    BiTreeNode* tot;
    BiTreeNode* Father;
    BiTreeNode* current;
    tot=(BiTreeNode*)malloc(sizeof(BiTreeNode));//the new point
    tot->data=data;
    tot->left=NULL;
    tot->right=NULL;
    Father=current=root;
    while (current!=NULL) { //find the leaf
        if (current->data<data) {
            Father=current;
            current=current->right;
        }
        else {
            Father=current;
            current=current->left;
        }
    }
    current=Father;

    if (current->data<data) {
        current->right=tot;
    }
    else {
        current->left=tot;
    }
}
int main()
{
    root=(BiTreeNode*)malloc(sizeof(BiTreeNode));
    root->data=10;
    root->left=NULL;
    root->right=NULL;
    Create(root,25);
    Create(root,5);
    Create(root,30);
    Create(root,12408);
    Create(root,233);
    cout<<233;
    return 0;
}

 

转载于:https://www.cnblogs.com/pityhero233/p/7305943.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值