Leecode 111.二叉树的最小深度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        //先判断是否为空
        if(root == null) {
            return 0;
        }
        int depth=0;
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int len  = que.size();
            depth ++;
            for (int i = 0; i < len; i++) {
                TreeNode node = que.poll();<br>       //判断两个子节点都为空则为叶子节点
                if(node.right == null && node.left == null ){
                    return depth;
                }
                if(node.left != null) {que.offer(node.left);}
                if(node.right != null) {que.offer(node.right);}
            }
        }
        return depth;
 
    }
}<br><br><br><br><br><br><br><br>//递归法<br><br><br>
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        //先判断是否为空
        if(root == null) {
            return 0;
        }
      //递归法 
      int leftLenth = minDepth(root.left);
      int rightLenth = minDepth(root.right);

      //从处理中间节点
      
      //如果左节点为空,右不为空,说明不是最小深度
      if(root.left == null && root.right != null) {
          return rightLenth+1;
      }
      if(root.right == null && root.left != null) {
          return leftLenth +1;
      }

      return min(leftLenth,rightLenth) +1;

    }


    public int min(int leftLenth,int rightLenth) {
        return leftLenth < rightLenth ?leftLenth:rightLenth;
    }
}

  

posted @   NOE42  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示