Sum Of Left Leaves
To solve this coding challenge, we need to compute the sum of all left leaves in a given binary tree. A left leaf is defined as a leaf node that is the left child of its parent. We will use a depth-first search (DFS) to traverse the tree and keep track of which nodes are left children.
Explanation
To solve this problem, we must traverse the binary tree and identify which nodes are left leaves. A leaf node is a node with no children. We will use a depth-first search (DFS) approach, which can be implemented both recursively or iteratively. Hereβs a step-by-step breakdown of our approach:- Initiate a sum variable to keep track of the sum of left leaves.
- Perform a depth-first search (DFS) starting from the root node.
- Use a helper function in our DFS to:
- Determine if the current node is a leaf node.
- Check if it is a left child.
- If it is a left leaf, add its value to the sum.
- Continue the DFS for the left and right children of the current node, while keeping track of whether each child is a left child or not.
- Return the sum once the entire tree has been traversed.
-
Define a function
sumOfLeftLeaves
-
Initialize a variable
sum
-
Define a nested helper function
dfs
-
In the
dfs
-
Return immediately if the node is
null
- Check if the current node is a leaf node (i.e., has no children).
-
If the node is a leaf and is a left child, add its value to
sum
-
Recursively call
dfs
-
In the main function, initiate the DFS process starting with the root node and a boolean value of
false
-
Return the final value of
sum
Detailed Steps in Pseudocode
Detailed Pseudocode with Comments
# Function to find the sum of left leaves in a binary tree
sumOfLeftLeaves(root):
# Initialize the sum to 0
sum = 0
# Define the DFS function to traverse the tree
dfs(node, isLeft):
# If the current node is null, return
if node is null:
return
# Check if the current node is a leaf node
if node.left is null and node.right is null:
# If the current node is a left leaf, add its value to the sum
if isLeft:
sum += node.val
# Return because it's a leaf node
return
# Recursively call dfs for the left child with isLeft=True
dfs(node.left, true)
# Recursively call dfs for the right child with isLeft=False
dfs(node.right, false)
# Start DFS with the root node and isLeft=false
dfs(root, false)
# Return the final sum
return sum
By following the above methodology, we ensure that we traverse every node in the tree. We specifically check if a node is a left leaf and add its value to our running total sum. This approach guarantees that all left leaves are accounted for in our final result.