A Binary Tree is a hierarchical data structure where each node has at most two children: left and right. Trees appear in about 30% of coding interviews! 🌳
💡 Think of it like this: A binary tree is like a family tree, but each person can have at most 2 children. The person at the very top is the root, and people at the bottom with no kids are called leaves.
💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
Key Tree Vocabulary:
The Big Secret: Almost every tree problem uses recursion. Why? Because the left subtree and right subtree are themselves trees! So you solve the same problem on smaller pieces.
This pattern of "do something with current node + recurse left + recurse right" is used in almost every tree problem. Master it! 💪
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 1 ← root
# / \
# 2 3 ← children of 1
# / \
# 4 5 ← children of 2 (3, 4, 5 are leaves)
count_nodes(root)
5
count_nodes(root.left)
3
count_nodes(None)
0