Leetcode 111. Minimum Depth of Binary Tree

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.
Note: A leaf is a node with no children.

题目大意:
查找一棵二叉树的最小深度,其定义为从根到最近的叶子的最短距离。注意,叶子的定义为没有子结点的结点。

解题思路:
递归返回根结点左右子树的最小深度,需要注意的是如果形如[1,2]即根结点只有一个子结点的情况,其最小深度为2。

代码:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root)
            return 0;
        if(!root->left)
            return 1 + minDepth(root->right);
        if(!root->right)
            return 1 + minDepth(root->left);
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
};

你可能感兴趣的:(Leetcode)