(BFS 简单)Leetcode 111. 二叉树的最小深度

在这里插入图片描述
我的方法是BFS做的,当然这个题目也可以采用递归的方法来做。

  • BFS
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        int mindep=0;
        if(root==nullptr)
            return mindep;
        queue<TreeNode*>que;
        que.push(root);
        int k=1;
        mindep=100000000;
        while(!que.empty())
        {
            
            vector<TreeNode*>vec;
            while(!que.empty())
            {
                root=que.front();
                que.pop();
                if(root->left==nullptr&&root->right==nullptr)
                    mindep=min(mindep,k);
                if(root->left)vec.push_back(root->left);
                if(root->right)vec.push_back(root->right);

            }
            k++;
            for(int i=0;i<vec.size();i++)
            {
                que.push(vec[i]);
            }
            
        }
        return mindep;

    }
};
  • 递归
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int minDepth(TreeNode* root) {
        int result=func(root);
        return result;
    }
    int func(TreeNode* root)
    {
        if(root==nullptr)
            return 0;
        if(root->left==nullptr&&root->right==nullptr)
            return 1;
        int mind=9999999;
        if(root->left!=nullptr)
            mind=min(mind,func(root->left));
        if(root->right!=nullptr)
            mind=min(mind,func(root->right));
        return mind+1;

    }
};

发布了741 篇原创文章 · 获赞 185 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/Fire_to_cheat_/article/details/103533914
今日推荐