111. Minimum Depth of Binary Tree
题干简述:
判断一个二叉树到其叶子结点的最短路径。
解题思路
通过递归获取根节点到叶子节点的路径长度,并取其中最小值。
题解
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var minDepth = function(root) {
if (!root) return 0;
const left = minDepth(root.left);
const right = minDepth(root.right);
if (left === 0 || right === 0) return left + right + 1; // 当左右子树最小高度有任意一个为 0 时,我们就无法通过 Math.min 进行对比,因为此时为 0 的子树实际上是不存在的;这是的结果应为不为 0 的子树的深度。
return Math.min(left, right) + 1;
};
Q.E.D.