[LeetCode] 111. Minimum Depth of Binary Tree

题目链接:传送门

Description

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.

Solution

题意:

求二叉树的最小深度

思路:

dfs

/**
 * 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 minDepth(root->right) + 1;
        if (!root->right)  return minDepth(root->left) + 1;
        int lDepth = minDepth(root->left);
        int rDepth = minDepth(root->right);
        return min(lDepth, rDepth) + 1;
    }
};
posted @ 2018-03-02 02:29  酒晓语令  阅读(68)  评论(0编辑  收藏  举报