一、主题
难度:简单
涉及知识:树、广度优先搜索
题目地址:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
题目内容:
给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [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; } - LeetCode Submit
执行用时 :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; };