LeetCode: Deepest Leaves Sum Solution

1/**
2 * Definition for a binary tree node.
3 * function TreeNode(val, left, right) {
4 * this.val = (val===undefined ? 0 : val)
5 * this.left = (left===undefined ? null : left)
6 * this.right = (right===undefined ? null : right)
7 * }
8 */
9/**
10 * @param {TreeNode} root
11 * @return {number}
12 */
13var deepestLeavesSum = function (root) {
14 let maxDepth = 0
15 let deepestLeavesSum = 0
16
17 const assignDepth = (node, depth = 0) => {
18 if (!node) return
19
20 maxDepth = Math.max(maxDepth, depth)
21 node.depth = depth
22 assignDepth(node.left, depth + 1)
23 assignDepth(node.right, depth + 1)
24 }
25 const getSum = node => {
26 if (!node) return
27
28 if (node.depth === maxDepth) deepestLeavesSum += node.val
29 getSum(node.left)
30 getSum(node.right)
31 }
32
33 assignDepth(root)
34 getSum(root)
35
36 return deepestLeavesSum
37}
38
39var deepestLeavesSum = function (root) {
40 let maxDepth = 0
41 const depthSum = {}
42
43 const traverse = (node, depth = 0) => {
44 if (!node) return
45
46 depthSum[depth] = (depthSum[depth] || 0) + node.val
47 maxDepth = Math.max(maxDepth, depth)
48 traverse(node.left, depth + 1)
49 traverse(node.right, depth + 1)
50 }
51
52 traverse(root)
53
54 return depthSum[maxDepth]
55}

Comments

Loading comments...

Tags

leetcode

tree

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Beautiful Arrangement II

HoningJS

Search Posts