Link: https://leetcode.com/problems/count-nodes-with-the-highest-score/
Solution:
Intuition
I really enjoyed this tree problem. I pretty much instantly knew how to solve it, but I spent a bit of time thinking about the optimal implementation from a memory standpoint.
The key idea here is that there can be at most only 3 components to consider:
- The number of nodes in the left subtree
- The number of nodes in the right subtree
- The number of nodes connected to the parent (above)
Number 1 and 2 are simple…we can just propagate a count from the leaves to the root, however #3 requires a little trick! The number of nodes in the “above” component will always be the total number of nodes subtracted by the number of nodes in the left component and the number of nodes in the right component…and -1
to subtract the current node!
above_count = n - left_count - right_count - 1
Basically, we can solve this recursively just as if we were solving for number of nodes in each subtree, but with some extra arithmetic to compute the score from the total.
There is one notable edge case. The root has no “above” component, so the derived formula will simplify to 0
! This is problematic because the score is a product, so we must handle the root as a special case.
Also, the problem statement is (strangely) asking for the total number of nodes with the max score, so we need to store all scores for all nodes in our traversal, and then perform a frequency analysis.
Implementation
Review 1
Cool problem, super annoying implementation! Also, you don’t need scores
hash map…some simple max logic and max_score, count
variables would suffice.