題目:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest...
題目:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
思路:
遞歸,註意是到leaf node,所以有一個孩子為空的話,則取非空的那一孩子
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)); } }