首页 > 其他 > 详细

计算二叉树的深度以及宽度

时间:2019-10-30 20:47:19      阅读:88      评论:0      收藏:0      [点我收藏+]
1)递归
int GetHeight(link root)
{
    if(NULL== root)
        return false;
    int left_count = GetHeight(root->ls)+1;
    int right_count = GetHeight(root->rs)+1;
    return left_count > right_count ? left_count : right_count ;
}
2)按层遍历
int GetAll(link root)
{
    if(NULL==root)
        return false;
    queue<link> q;
    int mx = -1,level = 0;
    q.push(root);
    while(!q.empty())
    {
        int ans = q.size(),
            cnt = 0 ;
        mx = max(mx,ans);
        while(cnt<ans)
        {
            link ptr =  q.front();
            q.pop(); cnt++;
            if(NULL!=ptr->ls)
                q.push(ptr->ls);
            if(NULL!=ptr->rs)
                q.push(ptr->rs);
        }
        level++;
    }
    return mx;
}

 

计算二叉树的深度以及宽度

原文:https://www.cnblogs.com/Shallow-dream/p/11767427.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!