(77)111. 二叉树的最小深度(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.

简单题 嗯 确实很简单 没什么好写的 写完后看了看题解 思路是一样的 看来没有什么骚操作 就这样吧

/**
 * 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值