递归算法:
int FindTreeDeep(BiTree BT){
int treeDeep=0;
if(BT){
int lchild=FindTreeDeep(BT->lchild);
int rchild=FindTreeDeep(BT->rchild);
treeDeep=lchild>=rchild?lchild+1:rchild+1;
}
return treeDeep;
}
非递归算法:
//后序非递归遍历,求出深度
void PostOrderTraverse(const BiTree T){
int treeDepth = 0; //记录树的深度
vector<BiTree> t_vTree;
BiTree p=T;
BiTree have_visited=NULL; //指示节点是否被访问
while (p || !t_vTree.empty())
{
if (p){
t_vTree.push_back(p);
p = p->lchild;
}
else{
p = t_vTree.back(); //此时P为空指针,将栈顶的节点弹出
if (p->rchild==NULL ||p->rchild==have_visited)
{
//如果深度比栈的深度小,将最大深度赋值为栈的深度
treeDepth = treeDepth<t_vTree.size()?t_vTree.size():treeDepth;
have_visited=p; //标记为已访问
t_vTree.pop_back();
p = NULL;
}
else p=p->rchild;
}
} //while
cout<<treeDepth<<endl;
}