https://www.bilibili.com/video/av46402848/
The first problem-solving approach
/ ** * A for binary Tree Node Definition. * Public class the TreeNode { * int Val; * the TreeNode left; * the TreeNode right; * the TreeNode (int X) {X = Val;} *} * / class Solution { public int minDepth (the TreeNode the root) { IF (the root == null) return 0; IF (root.left == null) return minDepth (root.right) + 1'd; //! ! ! ! ! Key left subtree is null see right subtree IF (root.right == null) return minDepth (root.left) +1; //! ! ! ! ! The key right subtree is null see left subtree int left = minDepth (root.left) +1; int right = minDepth (root.right) +1; return Math.min (left, right); //! ! ! ! ! The key } }
The second linked list traversal to achieve levels
class Solution { public int minDepth(TreeNode root) { int res = 0; if (root == null) return res; LinkedList<TreeNode> ll = new LinkedList<TreeNode>(); ll.add(root); while (!ll.isEmpty()) { int size = ll.size(); res++; // 要用两个while 的原因主要是增加层作用 while (size > 0) { TreeNode temp = ll.poll(); if (temp.left == null && temp.right == null) return res; if (temp.right != null) ll.add(temp.right); if (temp.left != null) ll.add(temp.left); size--; } } return res; } }