DFS
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } else if (root.left == null) { return minDepth(root.right) + 1; } else if (root.right == null) { return minDepth(root.left) + 1; } else { return Math.min(minDepth(root.left), minDepth(root.right)) + 1; } } }
|
BFS
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
| class Solution { public int minDepth(TreeNode root) { int depth = 0;
Queue<TreeNode> queue = new LinkedList<>(); if (root != null) { queue.offer(root); }
while (!queue.isEmpty()) { depth++; for (int i = queue.size(); i > 0; i--) { TreeNode node = queue.poll(); if (node.left == null && node.right == null) { return depth; } if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } }
return depth; } }
|
References
111. Minimum Depth of Binary Tree