标签:end else nbsp == init div nod oid body
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 1:
Input: {}
Output: 0
Example 2:
Input: {1,#,2,3}
Output: 3
Explanation:
1
\
2
/
3
/** * 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 */ int minDepth = Integer.MAX_VALUE; public int minDepth(TreeNode root) { if (root == null) { return 0; } else if (root.left == null && root.right != null) { helper(root.right, 2); } else if (root.right == null && root.left != null) { helper(root.left, 2); } else { helper(root, 1); } return minDepth; } public void helper(TreeNode root, int curDepth) { if (root == null) { return; } if (root.left == null && root.right == null) { if (curDepth < minDepth) { minDepth = curDepth; } return; } helper(root.left, curDepth + 1); helper(root.right, curDepth + 1); } }
public class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } return getMin(root); } public int getMin(TreeNode root){ if (root == null) { return Integer.MAX_VALUE; } if (root.left == null && root.right == null) { return 1; } return Math.min(getMin(root.left), getMin(root.right)) + 1; } }
Lintcode155-Minimum Depth of Binary Tree-Easy
标签:end else nbsp == init div nod oid body
原文地址:https://www.cnblogs.com/Jessiezyr/p/10676068.html