数据结构与算法——二叉树的实现(C++)

二叉树的实现

1 BinNode类

BinNode作为二叉树的节点,其定义的规范性十分基础又十分重要。以下是"binnode.h"中的程序内容。

#pragma once
#define BinNodePosi(T) BinNode<T>* //节点位置 
#define stature(p) ((p) ? (p)->height: -1) //节点高度

//BinNode状态与性质的判断
#define IsRoot(x) (!((x).parent))
#define IsLeaf(x) (!((x).lc || (x).rc))  
#define IsLChild(x) (!((x).parent) && (&(x) == (x).parent->lc))
#define IsRChild(x) (!((x).parent) && (&(x) == (x).parent->rc))
#define HasParent(x) ((x).parent) 
#define HasLChild(x) ((x).lc) 
#define HasRChild(x) ((x).rc) 
#define HasChild(x) (HasLChild(x) || HasRChild(x))                  //至少拥有一个孩子 
#define HasBothChild(x) (HasLChild(x) && HasRChild(x))              //同时拥有两个孩子 
#define sibling(p) (IsLChild(*(p)) ? (x).parent.rc: (x).parent.lc)          //兄弟 
#define uncle(p) (sibling((p).parent))                                              //叔叔 
#define FromParentTo(x)  ( IsRoot(x) ? _root : ( IsLChild(x) ? (x).parent->lc : (x).parent->rc ) )         //来自父亲的引用
 
typedef enum {
    RB_RED, RB_BLACK } RBColor; //节点颜色
 
template <typename T> struct BinNode{
   
	BinNodePosi(T) parent;
	BinNodePosi(T) lc;
	BinNodePosi(T) rc; //父亲、孩子
    int npl;
    RBColor color;
	T data; int height;  //高度、子树规模
    //构造函数
    BinNode():
        parent( nullptr ), lc( nullptr ),rc( nullptr ),height ( 0 ),npl( 1 ),color ( RB_RED ) {
   }
    BinNode( T e, BinNodePosi(T) p = nullptr, BinNodePosi(T) lc = nullptr, BinNodePosi(T) rc = nullptr, int h = 0, int l = 1, RBColor c = RB_RED):
        data( e ), parent( p ), lc( lc ), rc( rc ),height ( h ),npl( 1 ),color ( c ) {
   }
    //操作接口
    int size();
	BinNodePosi(T) insertAsLC( T const & ); //作为左孩子插入新节点
	BinNodePosi(T) insertAsRC( T const & ); //作为右孩子插入新节点
	BinNodePosi(T) succ(); //(中序遍历意义下)当前节点的直接后继
	template <typename VST> void travLevel(VST &); //子树层次遍历
	template <typename VST> void travPre(VST &); //子树先序遍历
	template <typename VST> void travIn(VST &); //子树中序遍历
	template <typename VST> void travPost(VST &); //子树后序遍历
};

//作为左孩子插入
template <typename T> BinNodePosi(T) BinNode<T>::insertAsLC(T const &e)
	{
   return lc = new BinNode( e, this);}
//作为右孩子插入
template <typename T> BinNodePosi(T) BinNode<T>::insertAsRC(T const &e)
	{
   return rc = new BinNode( e, this);}

//size()
template <typename T> int BinNode<T>::size(){
   //后代总数,以其为根的子树的规模
	int s =</
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值