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.
二叉树的最小路径问题 值得注意的一个地方是 当前根节点的左右孩子有一个为0 的时候 路径是朝向不为零的方向的
如果是叶子节点 那么就是left right均为0 所以会return1 均不为0 的情况是math.min
/**
* 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);
return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
}
}
本文介绍了一种求解二叉树最小深度的算法实现。该算法递归地计算左子树和右子树的最小深度,并根据左右子节点是否为空来决定返回路径长度。适用于所有二叉树结构。
1367

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



