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;
}
/******************************************************/
/*******************************************************/