/** * 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} */ const maxDepth = function (root) { }; /* 这非常符合递归操作,如需直到这颗数的最大深度,只需计算左右子树的深度中较大的,加上自己的这一层 不就是整颗数的深度吗? */ function f1(root) { if (!root) return 0; return Math.max(f1(root.left), f1(root.right)) + 1; } /* 利用BFS来查找每一层的所有节点,然后遍历所有每一层的所有节点,把查找是否有下一层节点,然后 把计数加1,直到这一层没有任何节点 */ function f2(root) { if (!root) return 0; const queue = [root]; // 初始化队列,将根节点加入队列 let depth = 0; while (queue.length > 0) { 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); // 如果右子节点存在,加入队列 } depth++; // 每完成一次层级遍历,深度加一 } return depth; }