• LeetCode.111. 二叉树的最小深度


    ​​​​​​111. 二叉树的最小深度

    难度:easy

     

     

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public int minDepth(TreeNode root) {
    18. // int minDepth = Integer.MAX_VALUE;
    19. if (root == null) {
    20. return 0;
    21. }
    22. Queue queue = new LinkedList<>();
    23. queue.offer(root);
    24. int depth = 0;
    25. while (!queue.isEmpty()) {
    26. int size = queue.size();
    27. // 层数+1
    28. depth++;
    29. for (int i = 0; i < size; i++) {
    30. TreeNode node = queue.poll();
    31. // 一个节点不存在左节点和右节点就可以计算深度;
    32. if (node.left == null && node.right == null) {
    33. // minDepth = Math.min(minDepth, depth);
    34. return depth;
    35. }
    36. if (node.left != null) {
    37. queue.offer(node.left);
    38. }
    39. if (node.right != null) {
    40. queue.offer(node.right);
    41. }
    42. }
    43. }
    44. return minDepth;
    45. }
    46. }

    在leetcode看到一个不错的题解,通过自行封装QueueNode加入depth信息,随时可以获得最短的深度。

    1. class Solution {
    2. class QueueNode {
    3. TreeNode node;
    4. int depth;
    5. public QueueNode(TreeNode node, int depth) {
    6. this.node = node;
    7. this.depth = depth;
    8. }
    9. }
    10. public int minDepth(TreeNode root) {
    11. if (root == null) {
    12. return 0;
    13. }
    14. Queue queue = new LinkedList();
    15. queue.offer(new QueueNode(root, 1));
    16. while (!queue.isEmpty()) {
    17. QueueNode nodeDepth = queue.poll();
    18. TreeNode node = nodeDepth.node;
    19. int depth = nodeDepth.depth;
    20. if (node.left == null && node.right == null) {
    21. return depth;
    22. }
    23. if (node.left != null) {
    24. queue.offer(new QueueNode(node.left, depth + 1));
    25. }
    26. if (node.right != null) {
    27. queue.offer(new QueueNode(node.right, depth + 1));
    28. }
    29. }
    30. return 0;
    31. }
    32. }

  • 相关阅读:
    什么是JavaScript中的闭包?
    springboot:自定义starter
    [数据结构] 树、森林及二叉树的应用
    【ROS入门】机器人系统仿真——URDF集成Gazebo
    feign 配置使用
    【python数据分析刷题】-N03.逻辑运算
    移动端H5页面调试vConsole
    荧光标记转铁蛋白-(FITC, cy3, cy5, cy7, 香豆素, 罗丹明)
    一、Hive优化
    IDEA下新建SpringBoot项目详细步骤
  • 原文地址:https://blog.csdn.net/weixin_45867071/article/details/126767954