Leetcode Problem 1302. Deepest Leaves Sum

1302. Deepest Leaves Sum

Leetcode Solutions

Approach: Iterative DFS Preorder Traversal

  1. Initialize a stack to store pairs of tree nodes and their corresponding depths.
  2. Push the root node onto the stack with a depth of 0.
  3. Initialize variables to keep track of the maximum depth encountered (max_depth) and the sum of the values of the deepest leaves (deepest_sum).
  4. While the stack is not empty: a. Pop the top element from the stack, getting the current node and its depth. b. If the current node is a leaf (no children): i. If the current depth is greater than max_depth, update max_depth and reset deepest_sum to the current node's value. ii. If the current depth is equal to max_depth, add the current node's value to deepest_sum. c. If the current node has a right child, push it onto the stack with a depth one greater than the current depth. d. If the current node has a left child, push it onto the stack with a depth one greater than the current depth.
  5. Return deepest_sum.
UML Thumbnail

Approach: Iterative BFS Traversal

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...