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.

Example:

Given binary tree [3, 9, 20, null, null, 15, 7] ,

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

解析:求二叉树的最小深度,采用深度优先的思路。因为这里求的最小深度指的是根节点到叶节点的路径,所以如果某个节点左子树为空,则返回右子树的最小深度+1.如果左右子树都不为空,则返回min(left_len, right_len)+1。

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
       if(root == NULL)
           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;
    }
};

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据