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.
Example
Given a binary tree as follow:
1
/
2 3
/
4 5
The minimum depth is 2
.
分治法来做,返回左右小的深度+1。
1.注意处理一侧子树为空的情况,不能就断言最短深度是1了,因为定义要求你一定要下到叶子节点。
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: The root of binary tree * @return: An integer */ public int minDepth(TreeNode root) { // write your code here if (root == null) { return 0; } int left = minDepth(root.left); int right = minDepth(root.right); // 切记处理一侧为空的情况,因为定义一定要走到叶子节点,所以此时不能就返回min = 1。以下处理即把0的那个排除掉。 if (left == 0 || right == 0) { return 1 + Math.max(left, right); } return 1 + Math.min(left, right); } }