这道题之前写过,但是之前只用了递归,现在只带递归是深度优先,这次特意看了其他的题解,找到了一个广度优先的,但是又点儿不明白,具体见代码..
/**
* 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) {
// 方法一 深度优先
// return root ? Math.max(maxDepth(root.left), maxDepth(root.right))+1 : 0;
//方法二 广度优先dfs
if(!root) return null;
let stack = [root];
let count = 0;
while(stack.length){
let size = stack.length;
// 这一步 不是很明白
while(size ){
let top = stack.shift();
if(top.left) {
stack.push(top.left);
}
if(top.right) { stack.push(top.right)}
size --;
}
count++
}
return count;
};