二叉树的三叉链表实现c语言,二叉树的几种表示法(二叉链表,三叉链表……)...

Tnode树的标准存储表示:

template

struct Tnode

{

typedef

std::vector CT;

CT children_;

T value_;

Tnode(T

const& v = T())

: children(), value_(v){ }

T&

value(void){ return value_; }

void add_child(Tnode* ch){ push_back(ch);

}

int degree(void) const

{

return

children_.size();

}

bool leafnode(void) const

{

return

children_.empty();

}

};

树《=》指向其根节点的指针;

先序遍历树:

template

NT>

void preorder(NT* root, void(*visit)(NT*))

{

typedef

typename NT::CT::iterator CI;

if(root != 0)

{

visit(root);

CI fc = root->children_.begin();

CI lc =

root->children_.end();

for(; fc != lc; ++fc)

preorder(*fc, visit);

}

}

后序遍历树:

template

NT>

void postorder(NT* root, void(*visit)(NT*))

{

typedef

typename NT::CT::iterator CI;

if(root != 0)

{

CI fc =

root->children_.begin();

CI lc =

root->children_.end();

for(; fc != lc; ++fc)

postorder(*fc, visit);

visit(root);

}

}

后续遍历求树的结点个数:

template

NT>

int size(NT* root)

{

if(root == 0)

return

0;

int result = 1;

typedef typename NT::CT::iterator CI;

CI

fc = root->children_.begin();

CI lc = root->children_.end();

for(; fc != lc; ++fc)

result += size(*fc);

return

result;

}

后序遍历求树的高度:

template

int height(NT*

root)

{

if(root == 0)

return 0;

int max = 0;

typedef typename NT::CT::iterator CI;

CI fc =

root->children_.begin();

CI lc = root->children_.end();

for(; fc != lc; ++fc)

{

int h = height(*fc);

if(h

> max)

max = h;

}

return max +

1;

}

/******************************************************/

/*******************************************************/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值