https://leetcode.com/problems/minimum-depth-of-binary-tree/
解题思路:
与 Maximum Depth of Binary Tree 这道题相反,是求二叉树的最小深度。贴两种写法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 1;
int left = root.left != null ? minDepth(root.left) : Integer.MAX_VALUE;
int right = root.right != null ? minDepth(root.right) : Integer.MAX_VALUE;
return Math.min(left, right) + 1;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int left = minDepth(root.left), right = minDepth(root.right);
return 1 + (Math.min(left, right) > 0 ? Math.min(left, right) : Math.max(left, right));
}
}