二叉树最小深度探究

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32621445/article/details/78074239

一、求解最小深度
题目是这样描述的: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

猜你喜欢

转载自blog.csdn.net/qq_32621445/article/details/78074239