碎碎念
倒霉熊不是停播了吗...
虽然今天pre还不错,但明天还有一场恶仗啊啊啊加油!
题目
代码
详细思路指路:【leetcode】104.二叉树的最大深度
这里就直接贴代码了。
DFS
/** * 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) { if (root === null) return 0 let l_depth = maxDepth(root.left) let r_depth = maxDepth(root.right) return Math.max(l_depth, r_depth) + 1 };BFS
/** * 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) { if (root === null) return 0 const q = [] q.push(root) let len = q.length let depth = 0 while (q.length > 0) { let len = q.length while (len > 0) { let node = q[0] if (node.left !== null) q.push(node.left) if (node.right !== null) q.push(node.right) q.shift() len-- } depth++ } return depth };