LintCode 155: Minimum Depth of Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roufoo/article/details/89787369
  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;
    }
};

猜你喜欢

转载自blog.csdn.net/roufoo/article/details/89787369