难度:简单bash
涉及知识:树、广度优先搜索ui
题目地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/spa
题目内容:code
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
复制代码
题目给定用例 [3,9,20,null,null,15,7]
输入方法的root元数据:
let root = {
val: 1,
left: {
val: 2, left: null, right: null
},
right: {
val: 3,
left: {
val: 4, left: null, right: {
val: 5,
left: {
val: 6, left: null, right: null
},
right: {
val: 7, left: null, right: null
}
},
},
right: {
val: 8, left: null, right: null
}
}
};复制代码
var maxDepth = function (root) {
if (!root) {
return 0;
}//检查输入的元数据
//初始化最大深度为1
let longestDepth = 1;
let getDepth = function (root, depth) {
if (!root) {
return;//检测输入该节点的值,若为空则表明此路线已遍历到底
}
if (root.left || root.right) {
depth += 1;
if (depth > longestDepth) {
longestDepth = depth;//当前遍历层级保持最大,由于有可能遍历回上层的depth
}
getDepth(root.left, depth);//优先遍历左侧子节点
getDepth(root.right, depth);
}
}
getDepth(root, 1);
return longestDepth;
}复制代码
执行用时 :200 ms, 在全部 JavaScript 提交中击败了5.23%的用户
内存消耗 :44.6 MB, 在全部 JavaScript 提交中击败了5.15%的用户复制代码
var maxDepth1 = function (root) {
if (!root) {
return 0;
}
return Math.max(maxDepth1(root.left), maxDepth1(root.right)) + 1;
};复制代码