Right Side View of Binary Tree in DSA C++ - Time & Space Complexity
We want to understand how the time needed to find the right side view of a binary tree changes as the tree grows.
How does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
void rightSideViewHelper(TreeNode* root, int level, vector& view) {
if (!root) return;
if (level == view.size())
view.push_back(root->val);
rightSideViewHelper(root->right, level + 1, view);
rightSideViewHelper(root->left, level + 1, view);
}
vector rightSideView(TreeNode* root) {
vector view;
rightSideViewHelper(root, 0, view);
return view;
}
This code visits nodes to collect the rightmost node at each level of the tree.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls visiting each node once.
- How many times: Each node in the tree is visited exactly one time.
As the number of nodes increases, the function visits each node once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The work grows linearly as the tree size grows.
Time Complexity: O(n)
This means the time to find the right side view grows directly with the number of nodes in the tree.
[X] Wrong: "Since we only look at the right side, the time is less than visiting all nodes."
[OK] Correct: The code still visits every node to check if it is the rightmost at its level, so all nodes are processed.
Understanding this time complexity helps you explain how tree traversal works and shows you can analyze recursive solutions clearly.
"What if we changed the traversal to visit the left child before the right child? How would the time complexity change?"