码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 111. 二叉树的最小深度

时间:2019-08-14 09:17:42      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:turn   nbsp   节点   efi   leetcode   二叉树   最小   imu   dep   

题目链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回它的最小深度  2.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 int minDepth(struct TreeNode* root){
10     if(root==NULL) return 0;
11     if(root->left==NULL&&root->right==NULL) return 1;
12     if(root->left==NULL&&root->right!=NULL) return 1+minDepth(root->right);
13     if(root->left!=NULL&&root->right==NULL) return 1+minDepth(root->left);
14     return minDepth(root->left)<minDepth(root->right)?minDepth(root->left)+1:minDepth(root->right)+1;
15 } 

 

LeetCode 111. 二叉树的最小深度

标签:turn   nbsp   节点   efi   leetcode   二叉树   最小   imu   dep   

原文地址:https://www.cnblogs.com/shixinzei/p/11349796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!