每日一题111. 二叉树的最小深度

111. 二叉树的最小深度

题目很简单,记录一下dfs和bfd,以及pair<a,b>的用法。

dfs

/**
 * 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) {
        if (root==NULL) return 0;
        if (!root->left && !root->right) return 1;
        int ans=0x3f3f3f3f;
        if (root->left) ans=min(ans,minDepth(root->left));
        if (root->right) ans=min(ans,minDepth(root->right)); 
        return ans+1;
    }
};

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) {
        if (root==NULL) return 0;
        queue<pair<TreeNode*,int> > q;
        q.push({root,1});
        //int ans=0x7fffffff;
        while (!q.empty())
        {
            TreeNode* rt=q.front().first;
            int depth=q.front().second;
            q.pop();
            
            if (!rt->left && !rt->right) 
                //ans=min(ans,depth);
                return depth;
            if (rt->left) q.push({rt->left,depth+1});
            if (rt->right) q.push({rt->right,depth+1});
        }
        //return 0;
        return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/hbhhhxs/article/details/108141655