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

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

View File

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