Count Nodes With the Highest Score — LeetCode 2049 Python Solution

MediumTreeDepth-First SearchArrayBinary Tree
Problem
#2049
Reading time
5 min

The problem

There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1.

Example

Input
parents = [-1,2,0,2,0]
Output
3
Explanation
- The score of node 0 is: 3 * 1 = 3

Python solution

Python
class Solution:
    def countHighestScoreNodes(self, parents: List[int]) -> int:
        def dfs(i: int, fa: int):
            cnt = score = 1
            for j in g[i]:
                if j != fa:
                    t = dfs(j, i)
                    score *= t
                    cnt += t
            if n - cnt:
                score *= n - cnt
            nonlocal ans, mx
            if mx < score:
                mx = score
                ans = 1
            elif mx == score:
                ans += 1
            return cnt

        n = len(parents)
        g = [[] for _ in range(n)]
        for i in range(1, n):
            g[parents[i]].append(i)
        ans = mx = 0
        dfs(0, -1)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2049. Count Nodes With the Highest Score is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2049. Count Nodes With the Highest Score?
LeetCode 2049. Count Nodes With the Highest Score is rated Medium on LeetCode.
What is the time complexity of LeetCode 2049. Count Nodes With the Highest Score?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2049. Count Nodes With the Highest Score?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2049. Count Nodes With the Highest Score cover?
LeetCode 2049. Count Nodes With the Highest Score is tagged Tree, Depth-First Search, Array and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview