码迷,mamicode.com
首页 > 其他好文 > 详细

[数据结构]求二叉树的深度与宽度

时间:2015-08-09 08:24:11      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:c++   二叉树   宽度   深度   

  二叉树数据结构声明:

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
};


  1、递归求二叉树深度

  

int getDepth(TreeNode *root)
{
    if (root == NULL)
    {
        return 0;
    }
    return getDepth(root->left) > getDepth(root->right) ?(getDepth(root->left) + 1) : (getDepth(root->right) + 1);
}
 2、宽度优先遍历求二叉树宽度

  宽度优先遍历,记录每一个层次的叶子节点,返回最大值

int getWidth(TreeNode *root)
{
    if (root == NULL)
    {
        return 0;
    }
    int width_up = 0;
    int temp = 0;
    int width_cur = 0;
    int width_res = 0;
    queue<TreeNode *> myQueue;
    myQueue.push(root);
    width_up = 1;
    width_res=1;
    TreeNode *temp_TreeNode = NULL;

    while (!myQueue.empty())
    {
        temp = width_up;
        while (temp != 0)
        {
            temp_TreeNode = myQueue.front();
            myQueue.pop();

            if (temp_TreeNode->left != NULL)
            {
                myQueue.push(temp_TreeNode->left);
            }

            if (temp_TreeNode->right != NULL)
            {
                myQueue.push(temp_TreeNode->right);
            }

            width_up--;
        }

        width_cur = myQueue.size();
        width_res = width_cur > width_res ? width_cur : width_res;
        width_up = width_cur;
    }

    return width_res;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[数据结构]求二叉树的深度与宽度

标签:c++   二叉树   宽度   深度   

原文地址:http://blog.csdn.net/er_plough/article/details/47372625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!