155. Minimum Depth of Binary Tree

比眉伴天荒 2022-05-27 04:53 302阅读 0赞

155. Minimum Depth of Binary Tree

Description

  1. Given a binary tree, find its minimum depth.
  2. The minimum depth is the number of nodes along the shortest
  3. path from the root node down to the nearest leaf node.

Example

  1. Given a binary tree as follow:
  2. 1
  3. / \
  4. 2 3
  5. / \ 4 5

Solution

  1. /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */
  2. public class Solution {
  3. /** * @param root: The root of binary tree * @return: An integer */
  4. public int minDepth(TreeNode root) {
  5. // write your code here
  6. if(root!=null){
  7. int mindl = minDepth(root.left);
  8. int mindr = minDepth(root.right);
  9. int mind = 0;
  10. //注意这里,和求最大深度不一样,如果左右子树有一棵为空,那么此时深度为非空的那棵子树的深度
  11. if(mindl==0||mindr==0) mind = mindl==0?mindr:mindl;
  12. else{
  13. mind = mindl>mindr?mindr:mindl;
  14. }
  15. return mind+1;
  16. }else{
  17. return 0;
  18. }
  19. }
  20. }

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读