Unbeaten on the Way Down
Medium · Trees & BSTs · about 15 min
A knockout tournament record is stored as a binary tree of scores, with the final at the root. A match is unbeaten if no match on the path from the root down to it (not counting itself) has a strictly higher score. The root is always unbeaten. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.
Return how many unbeaten nodes the tree has. An empty tree has 0.
- Up to 10,000 nodes, scores between -10,000 and 10,000.
Examples:
count_unbeaten([3, 1, 4, 3, None, 1, 5]) → 4 (3 at the root, 4, the lower 3, and 5)
count_unbeaten([3, 1, None, 2]) → 1
Hints
- What does a node need to know about the path above it? Just one number.
- Pass the biggest score so far down to the children, updated with the current score.
- What should that number start at so negative scores still work?
Learn the pattern first: the Trees & BSTs lesson.
More Trees & BSTs problems
- Levels in the Org Chart (Easy)
- Mirror the Folder Tree (Easy)
- Twin Backup Check (Easy)
- Exact Budget Trail (Easy)
- Shared Boss in the ID Tree (Easy)
- Floor-by-Floor Roster (Medium)
- Longest Handoff Chain (Medium)
- Shelf Index Check (Medium)
- K-th Cheapest Price (Medium)
- Closest Shared Folder (Medium)
- Rebuild the Bracket (Medium)
- Best Relay Route (Hard)
- Downhill Trails With a Target Sum (Hard)
- Office Wi-Fi Repeaters (Hard)