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

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;
}

 

posted @ 2019-10-30 20:13  __MEET  阅读(2020)  评论(0编辑  收藏  举报