題目:node
Given a binary tree, find its minimum depth.spa
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.rest
思路:code
遞歸,注意是到leaf node,因此有一個孩子爲空的話,則取非空的那一孩子blog
package tree; public class MinimumDepthOfBinaryTree { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null || root.right == null) return root.left == null ? (1 + minDepth(root.right)) : (1 + minDepth(root.left)); return Math.min(1 + minDepth(root.left), 1 + minDepth(root.right)); } }