原题链接在这里:https://leetcode.com/problems/minimum-depth-of-binary-tree/
本题与Maximum Depth of Binary Tree相似,不同是需要判断叶子节点,若是给出[1,2]这种情况,返回值应该是2而不是1,root的右节点为空,而根据定义:The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 此时root左节点不为空,所以root不能被认为是leaf.
AC Java:
/**
* 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);
int right = minDepth(root.right);
if(root.left == null){
return right + 1;
}
if(root.right == null){
return left + 1;
}
return Math.min(left,right)+1;
}
}

本文探讨了如何计算二叉树的最小深度,不同于最大深度的计算,它着重于找到从根节点到最近叶子节点的最短路径长度。通过递归方法解决此问题,对于空树返回0,对于非空树则比较左右子树的深度。
432

被折叠的 条评论
为什么被折叠?



