求二叉树的深度,递归与非递归算法

递归算法:

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;
}
    原文作者:递归算法
    原文地址: https://blog.csdn.net/mutex86/article/details/8163566
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞