Challenge - 5 Problems
Binary Tree Node Counter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateCount nodes in a simple binary tree
What is the output of the following code that counts total nodes in a binary tree?
DSA Python
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def count_nodes(root): if root is None: return 0 return 1 + count_nodes(root.left) + count_nodes(root.right) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(count_nodes(root))
Attempts:
2 left
💡 Hint
Count each node including root, left subtree, and right subtree.
✗ Incorrect
The tree has nodes 1, 2, 3, 4, and 5. Total nodes = 5.
❓ Predict Output
intermediateCount nodes in a skewed binary tree
What is the output of this code counting nodes in a skewed binary tree?
DSA Python
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def count_nodes(root): if root is None: return 0 return 1 + count_nodes(root.left) + count_nodes(root.right) root = Node(10) root.right = Node(20) root.right.right = Node(30) root.right.right.right = Node(40) print(count_nodes(root))
Attempts:
2 left
💡 Hint
Count all nodes along the right side.
✗ Incorrect
Nodes are 10, 20, 30, 40. Total nodes = 4.
🧠 Conceptual
advancedUnderstanding node count in a full binary tree
If a full binary tree has height 3 (root at height 1), how many total nodes does it have?
Attempts:
2 left
💡 Hint
Full binary tree nodes = 2^height - 1
✗ Incorrect
For height 3, nodes = 2^3 - 1 = 7.
🔧 Debug
advancedFind the error in counting nodes code
What error does this code produce when counting nodes in a binary tree?
DSA Python
class Node: def __init__(self, val): self.val = val self.left = None self.right = None def count_nodes(root): if root is None: return 0 return 1 + count_nodes(root.left) + count_nodes(root.left) root = Node(1) root.left = Node(2) root.right = Node(3) print(count_nodes(root))
Attempts:
2 left
💡 Hint
Check recursive calls carefully.
✗ Incorrect
The code calls count_nodes(root.left) twice, ignoring right subtree.
🚀 Application
expertCount nodes in a binary tree using iterative approach
Which option correctly counts total nodes in a binary tree using iteration (no recursion)?
DSA Python
class Node: def __init__(self, val): self.val = val self.left = None self.right = None root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5)
Attempts:
2 left
💡 Hint
Use a stack and increment count for each visited node.
✗ Incorrect
Option A uses a stack and increments count for each node visited. Option A uses pop() on list as queue but should use pop(0) to dequeue from front. Option A is recursive, not iterative. Option A never increments count, so returns 0.
