二叉树最小深度探究

一、求解最小深度
题目是这样描述的:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
采用两种方法解答:递归和非递归的方法
1、采用递归的方法:

class Solution {
public:
    int run(TreeNode *root) {
       if(root == NULL)
            return 0;
        if(root->left == NULL && root->right == NULL)
            return 1;

        int leftDepth = run(root->left);
        if(leftDepth == 0)
            leftDepth = INT_MAX;//防止左孩子为空,带来的影响

        int rightDepth = run(root->right);
        if(rightDepth == 0)
            rightDepth = INT_MAX;//防止右孩子为空,带来的干扰

        return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
    }
};

//另外一种写法:
class Solution {
public:
    int minDepth(TreeNode *root) {
        if (root == NULL) return 0;//根节点为空的情况
        if (root->left == NULL && root->right == NULL) return 1;//没有左右孩子的情况

        if (root->left == NULL) return minDepth(root->right) + 1;//没有左孩子,只有右孩子的情况。
        else if (root->right == NULL) return minDepth(root->left) + 1;//没有右孩子,只有左孩子的情况。
        else return 1 + min(minDepth(root->left), minDepth(root->right));//正常的情况
    }

};

2、非递归的方法

//层次遍历,先增加push,后删除pop.每遍历一层deepth增加1
class Solution {
public:
    int run(TreeNode *root) 
    {
        queue<TreeNode*> q;
        if(root==NULL) return 0;
        q.push(root);
        int deepth=0;
        while(!q.empty())//构成一个循环
            {
            int len=q.size();
            deepth++;
            while(len--)//内循环用来删除父节点,增加子节点
                {
                    TreeNode *tmp=q.front();
                    q.pop();
                    if(tmp->left!=NULL) q.push(tmp->left);
                    if(tmp->right!=NULL) q.push(tmp->right);
                    if(tmp->right==NULL && tmp->left==NULL) return deepth;
                }

            }
        return deepth;
    }
};

参考几位大佬的链接如下,感谢各位大佬的博客:
1、http://www.cnblogs.com/grandyang/p/4042168.html
2、http://www.cnblogs.com/felixfang/p/3887565.html
3、http://blog.csdn.net/fisherming/article/details/75096410(二叉树求深度的递归的详细分析,大佬关于递归调用的详解)
4、http://blog.csdn.net/brucehb/article/details/47453415

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值