思路
深度优先遍历中记录节点的层级
代码
先深度优先遍历一下
var maxDepth = function(root) {
const dfs = (n) => {
if(n){
log(n.val)
dfs(n.left)
dfs(n.right)
}
}
dfs(root)
};
加上l
每调用一下dfs就l+1
var maxDepth = function(root) {
let res = 0
const dfs = (n,l) => {
if(n){
if(!n.left && !n.right){
res = Math.max(res,l)
}
dfs(n.left,l + 1)
dfs(n.right,l + 1)
}
}
dfs(root,1)
return res
};
非递归
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
let res = 0
const dfs = (root) => {
if(root){
const stack = [[root,1]]
while(stack.length){
const [n,l] = stack.pop()
if(!n.left && !n.right){
res = Math.max(res,l)
}
if(n.left) stack.push([n.left,l+1])
if(n.right) stack.push([n.right,l+1])
}
}
}
dfs(root,1)
return res
};
复杂度
时间:O(n)
空间:O(n),函数调用函数的情况会自动形成一个栈