题解 | #二叉树的最大深度#
二叉树的最大深度
http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
// 层次遍历
function maxDepth( root ) {
// write code here
//深度
let depth = 0
//判空
if(!root) return depth
if(!root.left&&!root.right) return 1
//保存当前层节点
let current = []
//保存下一层层节点
let next = []
current.push(root)
while(current.length||next.length){
while(current.length){
// 添加一个节点的左右孩子后就将其弹出
if(current[0].left) next.push(current[0].left)
if(current[0].right) next.push(current[0].right)
current.shift()
}
// current为空,说明当前层遍历完
depth++
current = next
next = []
}
return depth
}