题目:
题目截图:
解题步骤:
1.广度优先遍历整棵树,并记录每个节点的层级
2.遇到叶子节点,返回节点层级,并停止遍历
代码:
/**
* 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 q = [[root, 1]];
while (q.length) {
const [n, l] = q.shift();
if (!n.left && !n.right) return l;
if (n.left) q.push([n.left, l + 1]);
if (n.right) q.push([n.right, l + 1]);
}
};
时间复杂度分析:
时间复杂度是O(n),n是节点的个数
空间复杂度分析:
空间复杂度是O(n)
怎么样,是不是很简单,你学会了吗 ?
如果这篇文章能够帮助到您,希望您不要吝惜点赞👍👍和收藏💖💖,您的支持是我继续努力的动力 💪💪!!!