/** * Временная сложность: O(N) * Пространственная сложность: O(W) (ширина дерева) */var maxDepth = function(root) { if (!root) return 0; const queue = [root]; let depth = 0; while (queue.length > 0) { depth++; // Начали новый уровень const levelSize = queue.length; // Фиксируем количество узлов на ЭТОМ уровне // Обрабатываем все узлы текущего уровня for (let i = 0; i < levelSize; i++) { const node = queue.shift(); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } } return depth;};
Решение 3 (DFS)
var maxDepth = function(root) { if (!root) return 0; const stack = [ [root, 1] ]; let maxD = 0; while (stack.length) { const [node, currentDepth] = stack.pop(); if (node) { maxD = Math.max(maxD, currentDepth); stack.push([node.left, currentDepth + 1]); stack.push([node.right, currentDepth + 1]); } } return maxD;};