LintCode 155: Minimum Depth of Binary Tree

  1. Minimum Depth of Binary Tree
    中文English
    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.

Example
Example 1:

Input: {}
Output: 0
Example 2:

Input: {1,#,2,3}
Output: 3
Explanation:
1
\
2
/
3
it will be serialized {1,#,2,3}
Example 3:

Input: {1,2,3,#,#4,5}
Output: 2
Explanation:
1
/ \
2 3
/
4 5
it will be serialized {1,2,3,#,#,4,5}

解法1:DFS。
注意,直接写成
int minDepth(TreeNode * root) {
if (!root) return 0;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
不对,因为1,#,3这样的情况会返回1。

代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: The root of binary tree
     * @return: An integer
     */
    int minDepth(TreeNode * root) {
        if (!root) return 0;
        if (!root->left) return minDepth(root->right) + 1;
        if (!root->right) return minDepth(root->left) + 1;
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
};

二刷:

class Solution {
public:
    int minDepth(TreeNode* root) {
       if (!root) return 0;
       helper(root, 0);
       return min_depth;
    }
void helper(TreeNode* root, int depth) {
    if (!root) return;
    depth++;
    if (!root->left && !root->right) {
        min_depth = min(min_depth, depth);
        return;
    }
    
    helper(root->left, depth);
    helper(root->right, depth);    
    depth--;
}
private:
    int min_depth = INT_MAX;
};

也可以

class Solution {
public:
    int minDepth(TreeNode* root) {
       if (!root) return 0;
       helper(root, 1);
       return min_depth;
    }
void helper(TreeNode* root, int depth) {
    if (!root) return;
    if (!root->left && !root->right) {
        min_depth = min(min_depth, depth);
        return;
    }
    
    helper(root->left, depth + 1);
    helper(root->right, depth + 1);    
}
private:
    int min_depth = INT_MAX;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值