二叉树的最小深度

二叉树的最小深度

2023年6月22日发(作者:)

⼆叉树的最⼩深度给定⼀个⼆叉树,找出其最⼩深度。⼆叉树的最⼩深度为根节点到最近叶⼦节点的距离。样例给出⼀棵如下的⼆叉树: 1 /

2 3 / 4 5

这个⼆叉树的最⼩深度为 2【主要在递归时要注意,当有的节点有⼀个⼦树为空时,不是叶⼦节点要继续寻找】/**

* Definition of TreeNode:

* public class TreeNode {

* public int val;

* public TreeNode left, right;

* public TreeNode(int val) {

* = val;

* = = null;

* }

* }

*/

public class Solution {

/**

* @param root: The root of binary tree.

* @return: An integer.

*/

public int minDepth(TreeNode root) {

// write your code here

if(root==null)

return 0;

if(==null && ==null)

return 1;

int dep1=minDepth()+1;

int dep2=minDepth()+1;

if(dep1==1)//左空右不空

dep1=_VALUE;

if(dep2==1)

dep2=_VALUE;

if(dep1>dep2)

return dep2;

return dep1;

}

}

//⽹上学习的⽅法01.

02.

03.

04.

05.

06.

07.

08.

09.

public class Solution {

public int minDepth(TreeNode root) {

if(root == null) return 0;

if( == null)return minDepth() + 1;

if( == null) return minDepth() + 1;

return (minDepth(), minDepth()) + 1;

}

}

发布者:admin,转转请注明出处:http://www.yc00.com/news/1687384400a6048.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信