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

二叉树的最小深度。

使用递归求解:

如果根节点为空,返回0。

如果左节点为空,递归计算右节点。

如果右节点为空,递归计算左节点。

返回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 == nullptr)
            return 0;
        if (root->left == nullptr)
            return 1 + minDepth(root->right);
        if (root->right == nullptr)
            return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left), minDepth(root->right));
    }
};
// 6 ms

 

posted @ 2017-10-17 16:01  immjc  阅读(110)  评论(0编辑  收藏  举报