refactor: 0102.二叉树的层序遍历

This commit is contained in:
qiufeihong2018
2024-04-29 18:19:48 +08:00
parent 4ca945f998
commit 2d37cd39e0

View File

@ -2809,21 +2809,23 @@ func maxDepth(root *TreeNode) int {
* @param {TreeNode} root * @param {TreeNode} root
* @return {number} * @return {number}
*/ */
var maxDepth = function(root) { var maxDepth = function (root) {
// 最大深度就是二叉树的层数 // 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
if (root === null) return 0; let max = 0,
let queue = [root]; queue = [root];
let height = 0; if (root === null) {
while (queue.length) { return max;
let n = queue.length; }
height++; while (queue.length) {
for (let i=0; i<n; i++) { max++;
let node = queue.shift(); let length = queue.length;
node.left && queue.push(node.left); while (length--) {
node.right && queue.push(node.right); let node = queue.shift();
} node.left && queue.push(node.left);
node.right && queue.push(node.right);
} }
return height; }
return max;
}; };
``` ```