We need to write a function that finds the sum of all nodes on the right side of the tree. But what does "right side of the tree" mean? Typically, "right side view" of a binary tree is the set of nodes that are visible when looking at the tree from the right side. That is, for each level, the rightmost node. But the problem says "sum of all nodes on the right side". It might mean sum of all nodes that are visible from the right side, i.e., sum of rightmost nodes at each level. Or it could mean sum of all nodes that are in the right subtree? That would be sum of all nodes in the right subtree of the root? But that seems too trivial: just traverse the right subtree and sum. However, the phrasing "on the right side of the tree" is ambiguous. In many coding problems, "right side view" is a common problem. But here they say "sum of all nodes" while the view problem returns a list of nodes. So it's plausible they want the sum of nodes in the right view. Alternatively, they might want the sum of all nodes that are on the right side of the tree, meaning nodes that are in the rightmost position at their level (i.e., visible from the right). I'll assume that's what they mean.
But let's think: Could it be "sum of all nodes on the right side" meaning sum of all nodes that are in the right subtree? That would be too simple: if the root is null, sum=0; otherwise, do a DFS on root.right. But why ask to write a function? That's trivial. Usually, if they wanted sum of right subtree, they'd say "sum of all nodes in the right subtree". The phrase "on the right side of the tree" could be interpreted as the right side view.
Let's check typical wording: "Right Side View" problem: "Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom." That returns a list. Here they ask for sum. So it's a variation: sum of those nodes.
Alternatively, "sum of all nodes on the right side" might mean sum of nodes that are directly on the right side, i.e., rightmost nodes at each depth. Yes.
Thus, the algorithm: perform a BFS (level order) and for each level, take the last node (rightmost) and add its value to sum. Or DFS, keeping track of level, and when we first visit a node at a new level from the right? Actually for right view, we need the rightmost node at each level. In DFS, we can traverse right subtree first and if we haven't recorded a node for that level, we take it. That's efficient. Or BFS straightforward.
I'll implement both conceptually, but BFS is simpler: use a queue, for each level, get the last node's value.
Time complexity: O(n) for both, but BFS uses extra space for queue, DFS uses recursion stack.
I'll write a function: def sum_right_side(root: Optional[TreeNode]) -> int
Define TreeNode class if needed.
But we need to output the function and explanation.
Let's provide Python code.
But before writing code, consider edge cases: empty tree -> sum 0.
Let's implement BFS:
Initialize sum = 0.
Queue = collections.deque([root]) if root else empty.
While queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
if i == level_size - 1: # last node in this level
sum += node.val
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
Return sum.
Alternatively, DFS:
def dfs(node, level):
nonlocal sum_result
if not node:
return
if level > len(seen_levels): # first time we reach this level from the right? Actually we traverse right first, so first node at a level is rightmost.
sum_result += node.val
seen_levels.append(level) # or simply track max level? Actually we can maintain a variable for current max level visited. If level > max_level: add node, max_level = level.
dfs(node.right, level+1)
dfs(node.left, level+1)
But careful: if we go right first, the first node we encounter at each depth is the rightmost (because we go as far right as possible). But if there is no right child at some level, we might need to consider left child? Actually rightmost node at a level is the node that appears last in a level order traversal from left to right. In DFS right first, when we first reach a new level, we are at the rightmost node because we prioritize right. However, if a level has only left children (no right), then when we go right first, we might go to a node that doesn't exist and then go left? But the DFS will still go to left child only after exhausting right subtree? Actually the algorithm: At a node, we first recurse on right child, then on left child. So for a given level, the first node visited will be the one that is furthest to the right along a path that goes as right as possible. But if at some level there is no node on the rightmost branch? For example:
1
/ \
2 3
/ /
4 5 6
7
Right view: 1,3,6,7? Let's see: level0:1, level1:3, level2:6, level3:7. At level2, the rightmost node is 6 (right child of 3). At level3, it's 7 (right child of 5, which is left child of 3). So rightmost node is not necessarily the right child of the rightmost parent? Actually it's the rightmost node at that level, i.e., with maximum horizontal position. In a level order, the rightmost node is the last node at that level.
If we do DFS right first, we will traverse 1->3->6->7 (if we go right then left, but after 6, we go to 6.left? none, 6.right? none, then back to 3, then 3.left? 5, then 5.right?7, then 5.left? etc). The first node at level0 is 1 (ok), first at level1 is 3 (right child of 1), first at level2: when we go from 3 to its right child 6 (level2) then that's first at level2. Then we go down to 6's children (none). Then we go to 3's left child 5 (level2) but we have already recorded a node for level2, so we skip 5. Then from 5 we go to 5.right 7 (level3) - that's first at level3. That matches right view. So DFS right first works.
But what if the rightmost node at a level is not on the rightmost branch? That can't happen: rightmost node at a level is by definition the node that appears last in a left-to-right order. If we do DFS right first, we'll eventually visit all nodes, but the order is: we go as deep as possible on the right, then backtrack and go left. So the first time we encounter a particular level, it will be the rightmost node at that level because we are exploring the rightmost paths first. Consider a case where right subtree is missing for some parent, but there is a left subtree that extends further right? Example:
1
/ \
2 3
/ /
4 5
6
Right view: level0:1, level1:3, level2:5, level3:6. Because at level2, nodes are 4 and 5, rightmost is 5. At level3, node 6 is under 5. DFS right-first: start at 1->right:3->right: none -> left:5->right:6-> then back to 5->left? none, back to 3-> left? already visited? Actually after finishing right subtree of 3 (which is none), we go to left child 5. At level2, first node visited is 5? Wait, when we go from 1->3, level1. Then at 3, we first try right (none), then left to 5 (level2). So the first node at level2 we encounter is 5. That's the rightmost at level2. That's fine. So DFS right-first works.
But what about a more complex scenario where the rightmost node at a level is actually a left child of some left-leaning parent? Example:
1
/ \
2 3
/ /
4 5 6
/ /
7 8 9
Let's draw: Actually let's construct a tree where the rightmost node at a level is not in the rightmost branch.
Consider:
1
/ \
2 3
/
4 5
/ \ /
6 7 8 9
But that's symmetrical. The rightmost at each level are: level0:1, level1:3, level2:5, level3:9. All are in the rightmost branch. That's typical because rightmost branch goes right as much as possible. But could it be that the rightmost node at level k is a left child? Suppose we have a node that has a left subtree that extends further right than any right subtree at that level? But the horizontal position is determined by left-right moves from root. If you go right from root, you get positive offset. If you go left, you get negative offset. The rightmost node at a given depth is the one with maximum offset. That offset is achieved by taking as many right moves as possible from the root. So the path to that node must be a sequence of right moves, except possibly at some point you might need to take a left? But to maximize offset, you want to go right as much as possible. The offset is (#right moves - #left moves). To maximize, you want to maximize number of rights and minimize lefts. So the path to the rightmost node at a given depth will have as many right moves as possible. That means it will go right as far as it can, and if it runs out of right children, it will have to go left. But then the node is a left child of some node that itself is reached by going right as much as possible. So the rightmost node may be a left child, but it's on the rightmost branch in the sense that the branch to it is the rightmost possible path. So DFS right-first (i.e., always try right child before left) will indeed encounter that node before any other node at the same depth, because we are exploring deeper along right paths first. So it's correct.
Thus DFS with right-first works.
But careful: In DFS, we need to track the level and add node value only when we encounter a level for the first time. Since we go right first, the first node at a given level is the rightmost. So we can maintain a variable max_level seen so far. When we visit a node at level > max_level, we add its value and update max_level.
Implementation:
def sum_right_side(root):
total = 0
max_level = -1
def dfs(node, level):
nonlocal total, max_level
if not node:
return
if level > max_level:
total += node.val
max_level = level
dfs(node.right, level+1)
dfs(node.left, level+1)
dfs(root, 0)
return total
But careful: The root level is 0, max_level starts -1 so level0 > -1 => add root, max_level=0.
That works.
But what if we have a tree where the rightmost node is missing at some level? That can't happen because each level must have at least one node if the tree has height >= level. Actually if the tree is not full, some levels might be missing? In a binary tree, levels are contiguous from 0 to height-1; there are no gaps because nodes are placed from top to bottom. So each level from 0 to max depth will have at least one node. So we will add exactly one node per level, total levels nodes.
But is that always? Consider a tree that is skewed left: all nodes are left children. The right view would be the leftmost nodes? Actually if tree is skewed left, there is no right child at any level except root? Let's take: root=1, left=2, left=3, left=4. So nodes: 1 (level0), 2 (level1), 3 (level2), 4 (level3). Right view? Since there is no right child at any level, the rightmost node at each level is actually the only node at that level, which is the left child. So right view would be [1,2,3,4]. That's consistent with our algorithm: DFS right-first: root (level0) added, then tries right (none), then left child 2 (level1). At node 2, level1 > max_level (0) => added, then right none, left child 3 (level2) added, etc. So sum includes all nodes. That is correct: right side view shows the nodes you would see if you look from the right side; if tree is left-skewed, you still see the leftmost nodes because there is nothing to block them. So that's correct.
Now, BFS approach: sum of last node in each level. That's also fine.
I'll provide both in explanation, but code likely one. I'll choose BFS for clarity.
Edge cases: empty tree => 0.
I'll write in Python.
But we need to define TreeNode? Usually in LeetCode, TreeNode is defined as:
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
I'll include that.
Now, the problem statement: "You are given a binary tree. Write a function to find the 'sum of all nodes' on the right side of the tree." Could also be interpreted as sum of all nodes that are in the right subtree? But I'll address ambiguity in explanation: we assume right side view. But I might mention that interpretation. But the answer should be code. Since it's a chat, I'll produce code that solves the right side view sum.
Alternatively, if they meant sum of all nodes that are on the right side, meaning the nodes that are in the right subtree (i.e., all descendants of root.right), then we'd do:
def sum_right_subtree(root):
if not root or not root.right:
return 0
total = 0
stack = [root.right]
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 would exclude the root if the root is considered? Usually root is not in right subtree. But the phrase "on the right side of the tree" might be ambiguous. In common parlance, "right side of the tree" could mean the right half? Or the rightmost nodes visible? I'd lean towards right view.
Let's search memory: There is a known problem "Sum of Right View Nodes" or "Sum of nodes visible from right side". Yes, I've seen modifications of Right Side View to sum.
Thus, I'll proceed with right view sum.
Now, algorithm explanation:
We need to compute the sum of nodes that are visible from the right side of the binary tree. When viewing from the right, at each level we can only see the rightmost node. So we need to identify the rightmost node at every level and sum their values.
We can do it using level order traversal (BFS). For each level, we know all nodes in that level. The last node in that level (or the rightmost) is the one that would be visible from the right. So while traversing each level, we keep track of the last node's value and add to sum.
Alternatively, we can use depth-first search (DFS) that traverses right subtree before left subtree. The first node encountered at each depth during this traversal is the rightmost node at that depth. We can maintain a variable to track the maximum depth visited so far; when we reach a node at a depth greater than max_depth, we add its value to sum and update max_depth.
Complexities: Both O(n) time, O(n) space in worst-case (BFS queue or DFS recursion). BFS may use up to width of tree in memory; DFS uses height.
I'll implement BFS as it's straightforward.
Now code:
from collections import deque
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_right_view(root: TreeNode) -> int:
if not root:
return 0
total = 0
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
# if it's the last node in this level, add to sum
if i == level_size - 1:
total += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return total
That's it.
I'll also provide DFS version in comment maybe.
But the problem says "Write a function to find the 'sum of all nodes' on the right side of the tree." So I'll provide the function.
Now explanation: we'll explain BFS and/ or DFS.
Let's produce final answer with code and explanation.
To find the sum of all nodes visible from the right side of a binary tree, we need to identify the rightmost node at each level (i.e., the node that would be seen if you looked at the tree from the right side). The sum of these nodes is the desired result.
Approach
We perform a level-order traversal (BFS) using a queue. For each level, we determine the last node (the rightmost node) by iterating through all nodes of that level. The value of that last node is added to the running total. After processing all levels, the total sum is returned.
Why it works:
In a BFS, nodes are visited from left to right within each level. The last node processed at a given level is exactly the rightmost node at that depth. By summing those values across all levels, we obtain the sum of the right-side view.
Complexity Analysis
- Time Complexity: O(n) – each node is visited exactly once.
- Space Complexity: O(w) – where
w is the maximum width (number of nodes at any level). In the worst case, the queue may store up to O(n) nodes, but typically it's O(width).
Code (Python)
from collections import deque
class TreeNode:
"""Binary tree node."""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_right_view(root: TreeNode) -> int:
"""
Returns the sum of values of nodes visible from the right side of the binary tree.
"""
if not root:
return 0
total = 0
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
node = queue.popleft()
# If this is the last (rightmost) node in the current level, add its value
if i == level_size - 1:
total += node.val
# Enqueue children for the next level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return total
Alternative DFS Solution
A depth-first search (DFS) that first visits the right subtree, then the left, can also be used. The first node encountered at each depth is the rightmost one. Below is a concise DFS implementation:
def sum_right_view_dfs(root: TreeNode) -> int:
total = 0
max_depth = -1
def dfs(node, depth):
nonlocal total, max_depth
if not node:
return
if depth > max_depth:
total += node.val
max_depth = depth
# Visit right first, then left
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)
dfs(root, 0)
return total
Both approaches run in O(n) time and O(n) space (BFS uses a queue; DFS uses recursion stack). The BFS version is often more intuitive for level-based problems.