You are given a binary tree. Write a function to find the "sum of all nodes" that are on the left side of the tree. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given a binary tree. We need to find the sum of all nodes that are on the left side of the tree.
But what exactly does "on the left side" mean? In many problems, "left side" might mean the leftmost nodes at each level, or all nodes that are in the left subtree of the root? The problem statement says "left side of the tree". That is ambiguous.
However, looking at the example? Actually, there's no example provided. Let me think about common interpretations.
Interpretation 1: All nodes that are in the left subtree of the root. But then what about the root? Usually the root is not considered on the left side. But if the tree has a root and then a left child and a right child, the left subtree includes all nodes under the left child.
Interpretation 2: The leftmost node at each level? That is a common problem: "Sum of Left Leaves" or "Sum of Leftmost Nodes". But the problem says "left side", which might be ambiguous.
Let me read the problem again: "sum of all nodes that are on the left side of the tree". Without more context, I'd assume they mean the leftmost node at each level? But then the example? Since no example, maybe it's a typical problem.
However, note: sometimes "left side" means all nodes that are visible from the left, i.e., the leftmost node at each depth. That is a common problem: "Binary Tree Left Side View" and then sum those nodes.
But the problem says "sum of all nodes", so if we take the left side view, we take one node per level.
Alternatively, it could be the sum of all nodes that are in the left subtree of the root (excluding the root). But then the root is not on the left side.
But wait, what if the root has no left child? Then the left side might be empty? That would be 0.
But let's think: if the tree is just a root, then the left side is empty? Or does the root count? Usually, the root is not considered on the left side unless it's the only node? Hmm.
Since the problem is ambiguous, I should clarify. But as an AI, I have to make an assumption.
I recall a similar problem: "Sum of Left Leaves" which is different. That's about leaves that are left children.
Another possibility: "Sum of all nodes that are left children of their parent". That is, for every node that is a left child (not necessarily leaf), add its value. But then the root has no parent, so it's not included.
Given the wording "on the left side of the tree", it might be the leftmost nodes at each level. Because when you look at the tree from the left, you see the leftmost node at each level.
I'll check online: There is a problem called "Sum of Left Leaves" and "Left Side View". But the problem says "left side", not "left leaves".
Since the problem says "binary tree", it could be any binary tree.
I think the most common interpretation for "left side" in the context of a tree is the leftmost node at each level. For example, if you draw the tree, the nodes that are on the left edge.
Let me define: The left side of a binary tree consists of the nodes that are the leftmost at their respective levels. That is, for each depth, the first node encountered in a level-order traversal from left to right.
How to get that? We can do a BFS (level-order) and for each level, take the first node.
But wait: what if a level has only one node? That's the leftmost.
So algorithm:
We traverse the tree level by level. For each level, we take the first node (the leftmost) and add its value to the sum.
Steps:
If the root is null, return 0.
Initialize a queue for BFS.
Enqueue the root.
While the queue is not empty:
Get the size of the current level (number of nodes at this level).
For i from 0 to size-1:
- Dequeue a node.
- If i == 0, then this is the leftmost node of the current level, so add its value to the sum.
- Enqueue the left child if exists.
- Enqueue the right child if exists.
Return the sum.
However, note: what about the root level? The root is at level 0. It is the only node at that level, so it is the leftmost. So we include the root.
But wait: is the root considered on the left side? In a tree with only a root, the left side is the root? That might be. But if the tree has a root and then a left child, the root is still the leftmost at level 0, and the left child is the leftmost at level 1? But note: at level 1, there are two nodes? Actually, if the root has both left and right, then at level 1, the leftmost is the left child. But if the root has only a right child, then at level 1, the leftmost is the right child? That doesn't sound like "left side". So perhaps we only consider nodes that are left children? But then the root is not a left child.
Alternatively, maybe the left side means the nodes that are in the leftmost path from the root to the leftmost leaf? That is, go left until you can't, then go right? That is the leftmost leaf path.
But the problem says "all nodes" on the left side, not a path.
Given the ambiguity, I think the BFS leftmost at each level is the most common interpretation for "left side view".
However, let's see the exact wording: "on the left side of the tree". It might also mean the left subtree. But then it would be "left subtree".
I think I need to ask for clarification, but since I can't, I'll assume the leftmost node at each level.
But wait, the problem says "sum of all nodes", so if we take one per level, that's a small sum. But if we take the entire left subtree, that could be many nodes.
Since the problem is from an interview context, maybe they want the left subtree.
Let me think about the example: if the tree is:
code
1
/ \
2 3
/ \ \
4 5 6
Then:
If we take leftmost at each level: level0: 1, level1: 2, level2: 4 -> sum = 1+2+4 = 7.
If we take the left subtree (root's left child and all its descendants): 2,4,5 -> sum = 11.
If we take all nodes that are left children (of their parent): 2 and 4 are left children? 2 is left child of 1, 4 is left child of 2, and 5 is right child of 2, so not included. Then sum = 2+4 = 6.
Which one is more likely? The problem says "left side of the tree". In the tree above, the left side would be the nodes 1,2,4? Because if you look from the left, you see 1, then 2, then 4. So that matches the leftmost at each level.
But note: at level2, the leftmost is 4. But 5 is also at level2 and is to the right of 4. So we don't see 5 from the left.
So I think the leftmost at each level is correct.
However, consider a tree where at some level, the leftmost node is not in the left subtree of the root? For example:
code
1
\
2
/ \
3 4
Then the leftmost at each level: level0:1, level1:2, level2:3. So sum=1+2+3=6.
But note that 2 is the right child of the root, and 3 is the left child of 2. So from the left, we see 1, then 2, then 3. That makes sense.
So in this case, the left side includes nodes that are not in the left subtree of the root? Actually, the root is the same, but at level1, the leftmost is the right child? That seems odd because the right child is on the right side. But from the left, if the root has no left child, then the next level we see the right child? Yes, because there's nothing on the left.
So the leftmost at each level is defined as: for each level, the node that appears first when traversing that level from left to right.
This is consistent.
Therefore, I'll implement the BFS method for leftmost at each level.
But wait: what if the tree is not perfect? We still do BFS and take the first node at each level.
Let's code accordingly.
However, note: the problem might also be interpreted as the left leaves. But the problem says "nodes", not "leaves".
So I'll go with the leftmost node at each level.
But to be safe, I should consider the possibility that the problem means the left subtree. Let me see the exact words: "left side of the tree". In some contexts, the left side of the tree is the left subtree. But then it would be the entire left subtree.
However, if it were the left subtree, they would likely say "left subtree". They say "left side", which is more visual.
Given that it's a common problem to get the left side view, I think that's it.
Let me write the function.
We assume the tree node structure as:
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
Then the function:
def sum_of_left_side(root: TreeNode) -> int:
if not root:
return 0
from collections import deque
queue = deque([root])
total_sum = 0
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
if i == 0:
total_sum += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return total_sum
But wait, in example2, at level2, the leftmost is 3, which is the left child of 2. So that's correct.
However, what if at level2, there was no left child? For example:
code
1
\
2
\
3
Then level0:1, level1:2, level2:3 -> sum=6.
But note: at level1, the node 2 is the right child of 1. So from the left, we see 1, then 2, then 3. That seems correct.
So the algorithm is consistent.
But wait: what if the tree has a node with only a right child at a level? Then the leftmost at that level is that right child? Yes.
However, consider a tree that is completely right-skewed:
1
2
3
Then the left side view would be 1,2,3. That is the same as the entire tree? But that's because the tree is skewed to the right and there are no left branches, so the leftmost at each level is just the only node.
But note: at level2, the node 5 is to the left of 4? No, because we traverse from left to right. We enqueue: for node 2, we enqueue left (4) and then for node 3, we enqueue left (5). So the queue for level2 is [4,5]. So the first is 4.
So that's fine.
Therefore, I think this is the intended solution.
However, I must note: the problem says "left side of the tree", and in some definitions, the left side might only include nodes that are in the leftmost path from the root to the leftmost leaf? That would be a single path. But then we would have to go left until we can't, then go right until we can't? That is the leftmost leaf path.
But the problem says "all nodes", so if we take the leftmost leaf path, we only get one node per level? Actually, the leftmost leaf path is a path from root to a leaf that is as left as possible. That path might not have a node at every level? Actually, it will have one node per level until it ends. But if the tree is not perfect, the leftmost leaf might be at a deeper level than other branches. So the path will have nodes at consecutive levels until the leaf. But then we would miss some levels? For example, if the leftmost leaf is at depth 3, then we have nodes at level0,1,2,3. But what about level4 if there is a node on the right at level4? That node would not be on the leftmost path.
But the problem says "on the left side", which might be interpreted as the leftmost nodes at each level, which might not form a connected path? Actually, they do form a path? Not necessarily. For example, in the tree:
code
1
/ \
2 3
/ /
4 5
The leftmost nodes are 1,2,4. That is a path: 1->2->4. But in the tree:
code
1
/ \
2 3
/ \ \
4 5 6
The leftmost nodes are 1,2,4. That is a path.
But in the tree:
code
1
/ \
2 3
/ /
4 5
/
6
The leftmost nodes:
level0:1
level1:2
level2:4
level3:6 -> so 1,2,4,6. That is a path? 1->2->4->6. Yes.
But what about:
code
1
/ \
2 3
/ /
4 5
\
6
Then level0:1, level1:2, level2:4, level3:6? But wait, at level3, we have node 6 which is the right child of 4. But in the level-order, we would have at level2: [4,5] and then at level3: [6] (from 4's right) and then from 5? 5 has no children. So level3: [6]. So leftmost at level3 is 6. So the path is 1->2->4->6. But note that 6 is not in the leftmost branch? Actually, the leftmost leaf path would be: 1->2->4->6? But 4 has a left? No, 4 has a right child 6. So the leftmost leaf is 6? But wait, what about the left subtree of 4? It's null, so the leftmost leaf in the entire tree? We have to go left until we can't. From root: left to 2, then left to 4, then left? 4 has no left, so then we go right? But the leftmost leaf is the leaf that appears first in an in-order traversal? Actually, the leftmost leaf is the leaf with the smallest value if we consider the tree as a BST? Not necessarily.
In a binary tree, the leftmost leaf is the leaf that you encounter first when doing a depth-first search going left first. That is: start at root, go left until you hit a leaf. If at a node you cannot go left, then go right until you hit a leaf.
So for the above tree:
Start at 1 -> left to 2 -> left to 4 -> 4 has no left, so then we check if 4 is leaf? No, it has a right child 6. Then we go to 6, which is a leaf. So the leftmost leaf is 6.
But wait, what about the node 5? 5 is at the same level as 4, but 4 is to the left of 5. So the leftmost leaf is 6? But 6 is under 4, which is the leftmost at level2. So the leftmost leaf is 6.
But then the leftmost nodes at each level: 1,2,4,6. That is exactly the path to the leftmost leaf.
But consider a tree where the leftmost leaf is not under the leftmost node at some level? For example:
The leftmost leaf path: from root, go left to 2, then left to 4, then left to 6 -> leaf. So the path is 1,2,4,6. That matches the leftmost at each level.
But what if:
code
1
/ \
2 3
/ /
4 5
\
6
We already did that, and the leftmost leaf is 6, and the leftmost nodes at each level are 1,2,4,6.
The leftmost leaf: from root, left to 2, left to 4 -> 4 is not a leaf (has no left? but has a right? Actually, in this tree, 4 has no children? Wait, we said 4 has no children? In the example I wrote: at node 4, it has no children? Actually, I wrote:
code
1
/ \
2 3
/ /
4 5
/
7
So node 4 has no children? Then 4 is a leaf? But then the leftmost leaf would be 4? But wait, we have a node 5 and then 7. But 4 is a leaf and is at level2. And it is the leftmost node at level2? Yes, because at level2 we have 4 and 5, and 4 is leftmost.
But then the leftmost leaf is 4, and the leftmost nodes at each level are: 1,2,4. We don't have a level3 because the leftmost leaf is at level2 and there is no leftmost node at level3? But wait, in the level-order traversal, at level3 we have node 7 (from 5's left). So we do have level3: [7]. So the leftmost at level3 is 7.
But the leftmost leaf is 4, which is at level2. So the leftmost nodes at each level (1,2,4,7) include 7, which is not on the path to the leftmost leaf.
So the leftmost nodes at each level and the path to the leftmost leaf can diverge.
Therefore, the two interpretations are different.
Given the problem says "on the left side", it might be the leftmost nodes at each level, which is a common problem (Left Side View). And the sum of those nodes.
But note: in the example above, the left side view would be 1,2,4,7. But is 7 on the left side? At level3, the leftmost node is 7, which is the left child of 5, which is the right child of 3. So 7 is in the right subtree of the root? But it is the leftmost at level3.
So from the left, we see 1, then 2, then 4, then 7? But wait, what about node 5? Node 5 is at level2 and is to the right of 4, so we don't see it. At level3, we see 7 because 5 has a left child and 4 has no children? But 4 has no children, so at level3, the only node is 7. So yes, we see 7.
Therefore, the left side view includes nodes that may not be in the left subtree of the root.
So I think the BFS method for leftmost at each level is the correct interpretation.
Let's code accordingly.
However, note: the problem might be expecting the left subtree sum. But without an example, I cannot be sure.
But given that the problem says "left side", I think it's the left view.
I'll write the function as described.
But wait, what if the tree is:
code
1
/ \
2 3
/ \ \
4 5 6
/ / /
7 8 9
Then leftmost at each level:
level0:1
level1:2
level2:4
level3:7,8,9? Wait, let's do BFS:
Start: [1]
Level0: take 1, then enqueue 2,3.
Level1: [2,3] -> take 2, enqueue 4,5 and then 3's children: 6? Actually, 3 has right child 6 and no left? So we enqueue 2's children: 4,5 and then 3's children: 6. So queue becomes [4,5,6].
Level2: [4,5,6] -> take 4, enqueue 7 (from 4's left) and then 5's children: 8? and 6's children: 9? So we enqueue 7, then 8, then 9. So queue: [7,8,9].
Level3: [7,8,9] -> take 7.
So the leftmost nodes: 1,2,4,7. Sum = 14.
But note: the left subtree of the root (root.left = 2 and all its descendants) would be: 2,4,5,7,8 -> sum = 26.
So clearly different.
Since the problem says "left side", I think the left view is more appropriate.
Therefore, I'll stick with the BFS leftmost at each level.
But let me see if there's a recursive way? We can do a DFS and keep track of the level, and when we first visit a level, we add the node's value.
Algorithm (DFS):
We maintain a variable max_level that tracks the maximum level we have visited so far. When we visit a node at level lvl, if lvl > max_level, then this node is the first node at this level (because we are doing a DFS that goes left first). But wait, if we do a DFS that goes left first, then the first node we encounter at a new level is the leftmost? Not necessarily, because the leftmost node at a level might not be the first one visited in a DFS if the tree is not complete. For example, in the tree:
code
1
/ \
2 3
/ /
4 5
If we do DFS (root, then left, then right) we visit: 1 (level0), then 2 (level1), then 4 (level2). Then we backtrack to 2 and then go to 5? But we already visited level2? So when we visit 5, the max_level is 2, so we don't add 5. That gives us 1,2,4. That matches the leftmost at each level.
But what about:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
DFS (left first):
1 (lvl0, max_level=-1 -> add, max_level=0)
then go left to 2 (lvl1, max_level=0 -> add, max_level=1)
then go left to 4 (lvl2, max_level=1 -> add, max_level=2)
then go left to 6 (lvl3, max_level=2 -> add, max_level=3)
then backtrack to 4, then 4 has no right? Then backtrack to 2, then go right to 5 (lvl2, but max_level=3, so not add).
Then from 5, go left to 7 (lvl3, max_level=3 -> not add because we already have a node at level3? But wait, we visited level3 first at node 6. So 7 is not the leftmost at level3? But in the tree, at level3, the leftmost node is 6? Yes, because 6 is under 4, which is the leftmost at level2. So 6 is the leftmost at level3.
So DFS with left-first and only adding when we reach a new level for the first time works.
But what if the tree is:
code
1
/ \
2 3
/ /
4 5
\
6
Then DFS left-first:
1 (lvl0, add)
2 (lvl1, add)
4 (lvl2, add)
then 4's left? none, then 4's right: 6 (lvl3, add) -> so we have 1,2,4,6.
But wait, at level3, the leftmost node is 6? But what about node 5? 5 is at level2 and has a left child? In this tree, 5 has no children? So at level3, we only have 6. So that's fine.
But what if:
code
1
/ \
2 3
/ /
4 5
/
6 7
Then DFS left-first:
1 (lvl0, add)
2 (lvl1, add)
4 (lvl2, add)
then 4's left: 6 (lvl3, add) -> then backtrack to 4, then 4's right? none, then backtrack to 2, then 2's right? none, then backtrack to 1, then go to 3 (lvl1, not add because max_level=3), then 3's left: 5 (lvl2, not add), then 5's right: 7 (lvl3, not add).
So we get 1,2,4,6. But the leftmost at level3 is 6? But wait, what about 7? 7 is at level3 and is to the right of 6? In the level-order, we would have at level3: [6,7]. So the leftmost is 6. So that matches.
So DFS with left-first and only adding when we reach a new level (i.e., the first time we visit a level) gives the leftmost node at each level.
But note: if we do DFS with left-first, we are essentially doing a pre-order traversal that goes left first. And the first node we encounter at a new level is the leftmost at that level? Yes, because we are going as left as possible. But what if at some level, the leftmost node is not in the leftmost branch? For example:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
In this tree, the leftmost at level2 is 4, and at level3 is 6. That's what we get.
But what if:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
8
Then at level3, we have 6 and 7. The leftmost is 6. But in DFS left-first, we visit 6 at level3 and add it. Then when we visit 7 at level3, we don't add because we already have a node at level3. But what if we had:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
8
/
9
Then at level4, the leftmost node is 8? But wait, 6 has a right child 8, and 7 has a left child? Actually, 7 has no left? We have 7 at level3, then 8 at level4? But 8 is the right child of 6. And 6 is at level3. So at level4, the leftmost node is 8? But what about 7? 7 has no children? Then at level4, the only node is 8? But wait, 6's right child 8 is at level4. And 7 has no children. So the leftmost at level4 is 8.
But in DFS left-first, we would visit 6, then 6's left? none, then 6's right: 8 (level4, add). Then we backtrack and visit 7 (level3, not add) and then 7's children? none. So we get 1,2,4,6,8. That matches.
However, consider a case where the leftmost node at a level is not visited first in a left-first DFS? That would happen if at some level, the leftmost node is not in the leftmost branch? But by definition, the leftmost node at a level is the one with the smallest horizontal position? And in a left-first DFS, we are always going to the leftmost branch first, so the first node we hit at a new level is the leftmost.
But wait, what if the tree is:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
8
/
9
We already did that.
But what if:
code
1
/ \
2 3
/ /
4 5
/ /
6 7
/
8
Then at level3, we have 6 and 7. The leftmost is 6. But in DFS left-first, we go to 6 first (from 4's left) and then later we go to 7 (from 5's left). So we add 6 at level3.
But what if the leftmost node at level3 is 7? That would require 6 to be to the right of 7? But 6 is under 4, which is the left child of 2, and 7 is under 5, which is the right child of 2? So 4 is to the left of 5, so 6 is to the left of 7. So 6 is the leftmost.
So in a binary tree, the leftmost node at a level is the one that is encountered first when doing a level-order traversal from left to right, and that is also the one that is in the leftmost branch? Not necessarily the leftmost branch in terms of the entire tree, but the one with the smallest horizontal position.
In a left-first DFS, we traverse the left subtree completely before the right subtree. So at each level, the first node we visit is the one that is in the leftmost branch? Yes, because we go left until we can't. So if we define the leftmost branch as the branch you get by starting at the root and always going left until you hit a null, then the nodes on that branch are the leftmost at their respective levels? Not necessarily: because if at some node we go left and then that node has a right child that is at the same level? Actually, the leftmost branch (root, then left child, then left child's left child, etc.) will give one node per level until it ends. But the leftmost node at a level might not be on that branch if at some level the leftmost branch does not have a node? For example, if the leftmost branch ends at level2, but at level3 there is a node in the right subtree? Then the leftmost node at level3 would be the leftmost node among all nodes at level3, which might be in the right subtree? But that node would have to be to the left of any node in the left subtree? But the left subtree at level3 might be empty? Then the leftmost node at level3 would be the leftmost node in the right subtree? And that node might not be on the leftmost branch (which ended at level2).
So in that case, the leftmost node at level3 is not on the leftmost branch (the branch that goes left until it can't). But in a left-first DFS, we would have finished the left subtree (which ends at level2) and then go to the right subtree. When we first enter the right subtree, we might be at level1? Wait, the root's right child is at level1. Then we go to its left child? That would be at level2? And then its left child at level3? So in the right subtree, we might have a node at level3 that is the leftmost at that level? But note: at level3, we have already visited the left subtree and found no node at level3? Then when we visit the right subtree and we reach a node at level3, that node is the first one we see at level3? But wait, we are doing DFS and we keep a global max_level. When we finish the left subtree, max_level might be 2 (if the leftmost branch ended at level2). Then when we go to the right subtree and we reach a node at level3, we will add it because level3 > max_level. But is that node the leftmost at level3? It might be the only node at level3? Or if there are multiple, we only take the first one we visit? But in a left-first DFS, we visit the leftmost node in the right subtree? Not necessarily. We visit the right subtree in a left-first manner too. So we go to the right child of the root, then its left child, then its left child's left, etc. So the first node we hit at level3 in the right subtree is the leftmost node in the right subtree at level3. But is that the leftmost at level3 overall? Since the left subtree had no node at level3, then the leftmost node in the right subtree at level3 is the leftmost at level3.
So the DFS method with left-first and tracking the max_level does give the leftmost node at each level.
Therefore, we can do either BFS or DFS.
I'll write both for completeness, but the problem asks for one function.
Since the problem says "write a function", I'll write the BFS version because it's straightforward.
But note: the BFS version uses a queue and is O(n) time and O(n) space (worst case when the tree is balanced, the last level has about n/2 nodes).
The DFS version uses recursion and the call stack, which in worst case is O(h) where h is the height, but we also need to store the result? We can just keep a running sum and a max_level variable. But we have to be careful because we are traversing the tree and updating a global max_level? We can do it with a class variable or by passing a mutable object.
I'll write the BFS version because it's easier to understand and doesn't rely on recursion stack.
However, the problem might be in a context where recursion is preferred? But without more information, I'll write BFS.
Let me write the code.
But wait: what about the root? In the BFS, we start with the root and we take the first node at level0, which is the root. So we include the root.
But is the root considered on the left side? In the left side view, the root is always included because it's the only node at level0.
So that's fine.
Now, what if the tree is empty? We return 0.
Let me code accordingly.
However, note: the problem says "binary tree", so we assume the TreeNode class as above.
I'll write the function in Python.
But the problem doesn't specify the language? It says "Write a function", so I'll write in Python as it's common.
Let me write:
from collections import deque
def sum_of_left_side(root):
if not root:
return 0
queue = deque([root])
total = 0
while queue:
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
if i == 0:
total += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return total
That's it.
But wait, what if the tree has negative values? The problem doesn't say, so we assume integers and we just sum.
Now, let's consider an alternative: if the problem meant the left subtree (all nodes in the left subtree of the root), then we would:
def sum_of_left_subtree(root):
if not root or not root.left:
return 0
# we want the sum of all nodes in the left subtree (including the left child but excluding the root)
# we can do a BFS or DFS on root.left.
total = 0
queue = deque([root.left])
while queue:
node = queue.popleft()
total += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return total
But note: the root is not included, only the left subtree.
Since the problem says "on the left side", I think the left view is more appropriate.
But to be thorough, I should mention the ambiguity in the explanation.
So in the explanation, I will state the assumption.
Explanation:
We assume that "left side of the tree" means the leftmost node at each level of the tree. This is also known as the left side view. We perform a level-order traversal (BFS) and for each level, we take the first node (the leftmost) and add its value to the sum.
Steps:
If the root is null, return 0.
Initialize a queue with the root.
While the queue is not empty:
a. Get the current level size (number of nodes in the current level).
b. For each node in the current level (from left to right):
i. If it is the first node in the level (i.e., index 0), add its value to the total sum.
ii. Enqueue its left and right children (if they exist) for the next level.
Return the total sum.
This algorithm runs in O(n) time and O(n) space, where n is the number of nodes in the tree.
However, if the problem intended the sum of all nodes in the left subtree (i.e., all nodes that are descendants of the root's left child), then we would simply traverse the left subtree and sum all nodes. But the phrasing "left side" is more commonly associated with the left view.
Given the ambiguity, I have chosen the left view interpretation.
If the problem intended the left subtree, then the function would be different.
But since the problem says "left side", I think left view is correct.
Let me adjust: what if the problem meant the left leaves? That is another common problem. But the problem says "nodes", not "leaves". So I think left view is the way.
I'll stick with the left view.
Final code:
Note: We use collections.deque for efficient popleft.
But if we are not allowed to use deque, we can use a list and pop(0) but that is O(n) per pop, so overall O(n^2). So we should use deque.
If we are in an environment without deque, we can simulate with two lists (current level and next level) to avoid popping from the front.
Alternatively, we can do:
current_level = [root]
while current_level:
next_level = []
total += current_level[0].val
for node in current_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current_level = next_level
This avoids deque and is still O(n) time and O(n) space.
Let me write that version to avoid importing deque.
But the problem doesn't specify if we can use deque. I'll write without deque.
So:
def sum_of_left_side(root):
if not root:
return 0
current_level = [root]
total = 0
while current_level:
total += current_level[0].val
next_level = []
for node in current_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current_level = next_level
return total
But if we intended the left subtree sum (excluding the root), then we would have: 2+3+4=9. So different.
So the left view sum is 1+2+3=6? Wait, in this tree, the leftmost at level2 is 3. So we take 3, not 4. So that's correct.
But note: the left subtree of the root (node 2 and its children) is 2,3,4 -> sum=9.
So indeed, the left view sum is different.
Therefore, I think the left view is the intended meaning.
I'll go with that.
But wait, what if the tree is:
code
1
/ \
2 3
/ \ \
4 5 6
/ / /
7 8 9
Left view: 1,2,4,7 -> sum=14.
Left subtree: 2,4,5,7,8 -> sum=26.
So they are different.
Since the problem says "left side", I think left view is more about the visual from the left.
So I'll finalize with the left view.
However, in the initial problem statement, it says "on the left side of the tree". It doesn't say "view". But I think it's the same.
Let me see if there's a standard problem called "Sum of Left Side Nodes". I recall a problem: "Sum of Left Leaves" and "Left Side View". But not exactly "Sum of Left Side".
Given that, I'll assume left view.
I'll write the code accordingly.
But note: the problem might be from a source that uses "left side" to mean left subtree. I cannot be sure.
Given the ambiguity, I'll state my assumption in the explanation.
So in the explanation, I will say:
We assume that the "left side" refers to the leftmost node at each level of the tree (i.e., the nodes that would be visible if you look at the tree from the left side). This is also known as the left side view.
If the problem intended the sum of all nodes in the left subtree (i.e., the subtree rooted at the left child of the root), then we would simply sum all nodes in that subtree. But the phrasing "left side" is more indicative of the left view.
I think it's safer to go with the left view because that's a common problem.
Let me write the function and explanation accordingly.
Final code (without deque):
def sum_of_left_side(root):
if not root:
return 0
current_level = [root]
total_sum = 0
while current_level:
# Add the value of the first node in the current level
total_sum += current_level[0].val
next_level = []
for node in current_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current_level = next_level
return total_sum
That's the function.
Now, the explanation:
We perform a level-order traversal (BFS) of the tree. For each level, we add the value of the first node (the leftmost node at that level) to the total sum. We continue until all levels are processed.
Time Complexity: O(n) where n is the number of nodes, because we visit each node exactly once.
Space Complexity: O(n) in the worst case (when the tree is balanced, the last level has about n/2 nodes).
If the tree is skewed, the space complexity is O(1) for the current level? Actually, in a skewed tree (like a linked list), at each level we have only one node, so the current_level list has at most 1 node. But in the worst case (complete binary tree), the last level has about n/2 nodes, so O(n).
Alternatively, we can use DFS with recursion and a variable to track the maximum level reached. But the BFS approach is straightforward.
I think that's it.
But wait, what about the root being the only node? Then we return root.val. That makes sense.
So I'll provide this solution.
However, if the problem intended the left subtree sum, then the function would be:
def sum_of_left_subtree(root):
if not root or not root.left:
return 0
total = 0
stack = [root.left]
while stack:
node = stack.pop()
total += node.val
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return total
But that's not what I'm going with.
Since the problem says "left side", I think the left view is correct.
I'll answer with the left view solution.
But to be safe, I'll mention in the explanation that we are assuming the left view.
Let me write the final answer.
We assume that "left side of the tree" refers to the leftmost node at each level (i.e., the nodes visible when viewing the tree from the left side, also known as the left side view). The solution uses a level-order traversal (BFS) to process the tree level by level, adding the value of the first node encountered at each level to the total sum.
Algorithm:
If the root is None, return 0.
Initialize current_level with the root node and total_sum = 0.
While current_level is not empty:
Add the value of the first node in current_level to total_sum (this is the leftmost node at the current level).
Prepare next_level by enqueueing all children (left then right) of every node in current_level.
Set current_level = next_level.
Return total_sum.
Complexity:
Time: O(n) – each node is visited exactly once.
Space: O(n) – in the worst case (complete binary tree), the last level contains ~n/2 nodes.
Example:
For the tree:
code
1
/ \
2 3
/ \ \
4 5 6
Level 0: leftmost = 1
Level 1: leftmost = 2
Level 2: leftmost = 4
Sum = 1 + 2 + 4 = 7.
Code:
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_of_left_side(root: TreeNode) -> int:
if not root:
return 0
current_level = [root]
total_sum = 0
while current_level:
total_sum += current_level[0].val # leftmost node of this level
next_level = []
for node in current_level:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current_level = next_level
return total_sum
Note: If the problem intended "left subtree" (all nodes in the subtree rooted at the root's left child), the solution would differ. However, based on common interpretations of "left side" in tree problems (e.g., left side view), the above approach is appropriate.