[Leetcode] 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.

思路

1、深度优先搜索:分别计算左子树的最小高度和右子树的最小高度,然后总的最小高度就是左子树最小高度和右子树最小高度的最小值加1。但是需要注意当左子树为空时,它不会构成一条路径的,此时不能参与最小高度的计算。右子树同理。

2、广度优先搜索:深度优先搜索的缺点是需要计算出来所有的最短路径,然后返回最小值。但实际上不需要计算所有的最短路径,广度优先搜索刚好可以解决这一问题。我们采用广度优先搜索逐层遍历节点,一旦发现叶子节点,就可以立刻返回当前叶子结点的高度(因为我们逐层遍历时,叶子所处的高度总是单调递增的)。

代码

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 == NULL) {
            return 0;
        }
        int min_depth_left = root->left? minDepth(root->left) : INT_MAX;
        int min_depth_right = root->right? minDepth(root->right) : INT_MAX;
        int min_depth = min(min_depth_left, min_depth_right);
        if (min_depth == INT_MAX) {
            return 1;
        }
        else {
            return min_depth + 1;
        }
    }
};

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 == NULL) {
            return 0;
        }
        int depth = 0;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        while (!q.empty()) {
            TreeNode *node = q.front();
            q.pop();
            if (node == NULL) {
                ++depth;
                if (!q.empty())
                    q.push(NULL);
            }
            else {
                if (!node->left && !node->right) {
                    return depth + 1;
                }
                else {
                    if (node->left)
                        q.push(node->left);
                    if (node->right)
                        q.push(node->right);
                }
            }
        }
        return depth;
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值