leetcode 111
思路
本题可以参考二叉树的最大深度
最小深度需要注意的一个点是,叶子节点表示的是左右节点都不存在的节点,在使用后序遍历时,如果根节点没有左子树,也就是leftDepth为0的时候,那就要取右子树的节点数+1,所以结果值需要进行一下特殊判断,而不是直接进行Math.min(leftDepth,rightDepth) + 1
方法1 后序遍历
var minDepth = function (root) {const deep = (root) => {if (!root) return 0;const leftDepth = deep(root.left)const rightDepth = deep(root.right);if (leftDepth === 0) {return rightDepth + 1;} else if (rightDepth === 0) {return leftDepth + 1} else {return Math.min(leftDepth, rightDepth) + 1;}}return deep(root)
};
方法2 层序遍历
var minDepth = function (root) {if(!root) return 0;const queue = [root];let depth = 0;while (queue.length) {depth++let len = queue.length;while (len--) {const node = queue.shift();node.left && queue.push(node.left)node.right && queue.push(node.right)// 当左右节点都没有的时候,说明到了叶子节点if (!node.left && !node.right) {return depth;}}}
};