求二叉树的深度

本文介绍了两种计算树深度的方法:递归法和非递归法。递归法通过比较左右子树深度并加一得到整棵树的深度。非递归法则使用队列实现层次遍历,每遍历完一层增加深度计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//树的深度
int TreeDepth(BTree* root) 
{ 
     int nLeft, nRight; 
     if(root == NULL)//必不可少的条件,递归的出口 
         return 0;   
     nLeft = TreeDepth(root->lchild); 
     nRight = TreeDepth(root->rchild); 
     return (nLeft > nRight) ? (nLeft + 1):(nRight + 1); 
} 

非递归写法

//树的深度
int TreeDepth(BTree* root) 
{ 
    if(root == nullptr)
        return 0;
    queue<TreeNode*> one,two;
    one.push(root);
    int res=0;
    TreeNode* tmp=root;
    while(!one.empty() || !two.empty())
    {
        if(!one.empty())
        {
            while(!one.empty())
            {
            tmp=one.top();
            if(tmp->left);
                two.push(tmp->left);
            if(tmp->right)
                two.push(tmp->left);
            one.pop();
            }
        res++;
        }
        if(!two.empty())
        {
            while(!two.empty())
            {
            tmp=two.top();
            if(tmp->left);
                one.push(tmp->left);
            if(tmp->right)
                one.push(tmp->left);
            two.pop();
            }
        res++;
        }
    }
    return res;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值