(77)111. The minimum depth of a binary tree (leetcode)

题目链接:
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
难度:简单
111. 二叉树的最小深度
	给定一个二叉树,找出其最小深度。
	最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
	说明: 叶子节点是指没有子节点的节点。
示例:
	给定二叉树 [3,9,20,null,null,15,7],
	    3
	   / \
	  9  20
	    /  \
	   15   7
	返回它的最小深度  2.

The simple question is really simple. There is nothing to write. After finishing writing, I looked at the problem solution and the idea is the same. It seems that there is no Sao operation.

/**
 * 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==nullptr){
    
    
            return 0;
        }
        return dfs(root,1);
    }

    int dfs(TreeNode* root,int d){
    
    
        if(root==nullptr){
    
    
            return d-1;
        }
        if(root->left==nullptr&&root->right==nullptr){
    
    
            return d;
        }else if(root->left!=nullptr&&root->right!=nullptr){
    
    
            int left=dfs(root->left,d+1);
            int right=dfs(root->right,d+1);
            return min(left,right);
        }else{
    
    
            int left=dfs(root->left,d+1);
            int right=dfs(root->right,d+1);
            return max(left,right);
        }
    }

};
class Solution {
    
    
public:
    int minDepth(TreeNode* root) {
    
    
        if(root==nullptr){
    
    
            return 0;
        }
        queue<pair<TreeNode*,int>> que;
        que.emplace(root,1);
        while(!que.empty()){
    
    
            auto a=que.front();
            TreeNode* node=a.first;
            int depth=a.second;
            que.pop();
            if(node->left==nullptr&&node->right==nullptr){
    
    
                return depth;
            }
            if(node->left!=nullptr){
    
    
                que.emplace(node->left,depth+1);
            }
            if(node->right!=nullptr){
    
    
                que.emplace(node->right,depth+1);
            }
        }
        return 0;
    }
};

おすすめ

転載: blog.csdn.net/li_qw_er/article/details/108138875