LeetCode 1302. Deepest Leaves Sum Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1302. Deepest Leaves Sum

Description

Given the root of a binary tree, return the sum of values of its deepest leaves.

 

Example 1:

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Example 2:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 1 <= Node.val <= 100

Solutions

Solution 1: BFS

We can use breadth-first search (BFS) to traverse the binary tree level by level, and calculate the sum of the node values at each level. After completing the traversal, return the sum of the node values at the last level.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the tree.

PythonJavaC++GoTypeScriptRust
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: q = deque([root]) while q: ans = 0 for _ in range(len(q)): node = q.popleft() ans += node.val if node.left: q.append(node.left) if node.right: q.append(node.right) return ans(code-box)

Solution 2: DFS

We can use depth-first search (DFS) to recursively traverse the binary tree while keeping track of the current node's depth, the maximum depth, and the sum of the deepest leaf nodes. When visiting the current node, if the current node's depth equals the maximum depth, add the current node's value to the sum of the deepest leaf nodes. If the current node's depth is greater than the maximum depth, update the maximum depth to the current node's depth and update the sum of the deepest leaf nodes to the current node's value.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the tree.

PythonJavaC++GoTypeScriptC
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: def dfs(root, i): nonlocal ans, mx if root is None: return if i == mx: ans += root.val elif i > mx: ans = root.val mx = i dfs(root.left, i + 1) dfs(root.right, i + 1) ans = mx = 0 dfs(root, 1) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !