【leetcode】【easy】111. Minimum Depth of Binary Tree

230 篇文章 0 订阅

111. Minimum Depth of Binary Tree

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

 

法一:DFS递归

递归思想的练习。非递归不写了。

相比求最大深度的题,本题多了一个小陷阱:深度代表的是从根节点出发到叶子节点结束。

特殊:[3,null,20,15,7],答案是3二不是1。

因此向上返回长度时,需要判断当前节点是否左右都有孩子,有则返回左右中较小深度,无则返回较大深度(较小值其实就是0)。

/**
 * 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;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        if(root->left && root->right) return min(l,r)+1;
        else return max(l,r)+1;
    }
};

 

法二:BFS

一个小坑:左右只有一边有孩子时,以有孩子的那边的深度为准,所以要从是否叶子节点的角度出发。

例如:[3,null,20,15,7]答案为3 不为1,[1,2,3,4,null,null,5]答案为3 不为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) return 0;
    	queue<TreeNode*> q;
        q.push(root);
        int dep = 1;
        while(!q.empty()){
            int len = q.size();
            for(int i=0; i<len; ++i){
                auto node = q.front();
                q.pop();
                if(!node->left && !node->right){
                    return dep;
                }
                if(node->left)q.push(node->left);
                if(node->right)q.push(node->right);
            }
            ++dep;
        }
        return dep;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值