求二叉树的高度(递归与非递归)

本文介绍了两种计算二叉树高度的方法:非递归和递归。非递归方法使用队列进行层序遍历,递归方法通过左右子树的最大高度确定整棵树的高度。

非递归采用层序遍历的思想,当遍历到某一层的最后一个元素时与last(初值为1,这里采用的队列为空的条件为Q.rear=Q.front=0)相等则高度加1,若其子树不为空则入队,最后入队的又为该层的最后一个元素。
递归则分别递归其左右子树,其中较大值加1即为树的高度。

//求二叉树的高度(非递归)
int high(BiTree T){
	Queue Q;
	InitQueue(Q);
	int last=1,level=0;
	EnQueue(Q,T);
	BiTree p;
	while(!isEmptyQueue(Q)){
		DeQueue(Q,p);
		if(p->lchild) EnQueue(Q,p->lchild);
		if(p->rchild) EnQueue(Q,p->rchild);
		if(Q.front==last){
			level++;
			last=Q.rear;
		}
	}
	printf("该二叉树的高度为:%d\n",level);
	return level;
}

//求二叉树的高度(递归)
int high_rescursion(BiTree T){
	if(T){
		int lhigh=high_rescursion(T->lchild);
    	int rhigh=high_rescursion(T->rchild);
    	if(lhigh>rhigh) return lhigh+1;
    	else return rhigh+1;
	}
	return 0;
} 
// 另外一种非递归,Java版的
 public static int depth_Non(BinTree T) {
        // 非递归
        Queue<BinTree> Q = new Queue<>(20); // 大小为20
        BinTree p = null;
        int deep = 0;
        Q.EnQueue(T);
        while (!Q.isEmpty()) {
            // size标记一层的数量,当处理完这一层deep就加1
            int size = Q.length();
            while (size>0) {
                p = Q.DeQueue();
                if (p.left != null) Q.EnQueue(p.left);
                if (p.right != null) Q.EnQueue(p.right);
                size--;
            }
            deep++;
        }
        return deep;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值