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 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

 

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

 

 

 

 

 

思路1:

这是比较好的练手题,DFS和BFS都可以做,先讨论DFS。首先如果当前root为空,则这一层不算,返回0。如果只有左,则返回当前一层1+往左递归;如果只有右,返回当前一层1+往右递归;左右都有则返回当前一层1+左右中相对小的一种情况即可。优点是代码比较短,不用额外空间,只需要函数内递归栈即可,但是缺点显然是运行较慢,需要遍历所有可能情况。

 

 

 

 

 

代码1:

/**
 * 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;
        if(!root->left) 
            return 1 + minDepth(root->right);
        if(!root->right) 
            return 1 + minDepth(root->left);
        return 1+min(minDepth(root->left),minDepth(root->right));
    }
};

 

 

 

 

思路2:

用队列模拟BFS。先检查初始root,为空直接返回0,否则记depth为1。之后就是常规的BFS,如果当前node是叶子节点,直接返回当前depth;否则如果有左就把左加入队列,有右就把右加入队列即可。最后返回depth。

 

 

 

 

代码2:

/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}

 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}

 * };

 */

class Solution {

public:

    int minDepth(TreeNode* root) {

        if(!root)

            return 0;

        int depth=1;

        queue<TreeNode*> q;

        q.push(root);

        while(q.size())

        {

            int len=q.size();

            for(int i=0;i<len;i++)

            {

                auto t=q.front();

                q.pop();

                if(!t->left&&!t->right)

                    return depth;

                if(t->left)

                    q.push(t->left);

                if(t->right)

                    q.push(t->right);

            }

            depth++;

        }

        return depth;

    }

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值