题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
思路:BFS(广度优先搜索)在遍历的时候,会增加每个节点的level信息,然后把每个「叶子节点」的level数都丢到一个max数组中,最后从max数组中找到最大的数返回。
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(root === null) return 0;
let stack = [];
let level = 1;
let max = [];
stack.push([level, root]);
while(stack.length > 0) {
let pop = stack.pop();
let node = pop[1];
level = pop[0];
// 如果当前节点是「叶子节点」,则把当前节点的level放到max数组中
if(node.left === null && node.right === null) {
max.push(level);
} else {
level += 1;
if( node.left !== null) {
stack.push([level, node.left]);
}
if( node.right !== null) {
stack.push([level, node.right]);
}
}
}
return Math.max(...max);
};
网友评论