不同语言树结构的定义

这篇博客探讨了C++中两种不同的树结构定义,包括基于数组和链表的二叉树实现,并对比了Python的树结构。通过链接提供了详细的代码参考。
摘要由CSDN通过智能技术生成

C++

struct TreeNode{
TYPE element;//该节点的元素
TreeNode *firstChild;//指向该节点的第一个孩子
TreeNode *nextSibling;//指向该节点的兄弟节点
};

C++还有比较完整的树定义(代码参考https://www.jianshu.com/p/1cbd86da13bd)

//Tree.h 文件
#pragma once
#include <list>
#include <algorithm>
using namespace std;

struct TreeNode;   //定义一个结构体原形
class Tree;        //定义一个类原形
class Iterator;    //定义一个类原形
typedef list<TreeNode*> List; //重命名一个节点链表

TreeNode* clone(TreeNode*, List&, TreeNode*);//Clone复制函数

struct TreeNode {
    int _data;                         //数据
    TreeNode* _parent;                 //父节点
    List _children;                    //子节点
    TreeNode(int, TreeNode* );          //构造函数
    void SetParent(TreeNode& );         //设置父节点
    void InsertChildren(TreeNode& );    //插入子节点
};

class Tree{
public:

    //下面是构造器和运算符重载
    Tree();                                //默认构造函数
    Tree(const Tree&);                     //复制构造函数
    Tree(const int);                       //带参数构造函数
    Tree(const int,const list<Tree*>&);    //带参数构造函数
    ~Tree();                               //析构函数
    Tree& operator=(const Tree&);           //=符号运算符重载
    bool operator==(const Tree&);           //==符号运算符重载
    bool operator!=(const Tree&);           //!=符号运算符重载

                                        //下面是成员函数
    void Clear();                         //清空
    bool IsEmpty()const;                  //判断是否为空
    int Size()const;                      //计算节点数目
    int Leaves();                         //计算叶子数
    int Root()const;                      //返回根元素
    int Height();                         //计算树的高度


                                      //下面是静态成员函数
    static bool IsRoot(Iterator);         //判断是否是根
    static bool isLeaf(Iterator);         //判断是否是叶子
    static Iterator Parent(Iterator);     //返回其父节点
    static int NumChildren(Iterator);     //返回其子节点数目

                                     //跌代器函数
    Iterator begin();                //Tree Begin
    Iterator end();                  //Tree End
    friend class Iterator;            //Iterator SubClass
private:
    list<TreeNode*> _nodes;            //节点数组
    list<TreeNode*>::iterator LIt;     //一个节点迭代器
    int height(TreeNode*);
    int level(TreeNode*,Iterator);
};

//This is TreeSub Class Iterator
class Iterator{
privat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值