## Similar Problems

Similar Problems not available

# Count Nodes With The Highest Score - Leetcode Solution

## Companies:

LeetCode: Count Nodes With The Highest Score Leetcode Solution

Difficulty: Medium

Topics: tree binary-tree array depth-first-search

The Count Nodes With The Highest Score problem on LeetCode states that we are given a binary tree with n nodes and each node of the tree contains a score. Our aim is to find the number of nodes in the tree that have the highest score.

To solve this problem, we can traverse the tree using any traversal technique and keep track of the maximum score while traversing. We can maintain a count variable that stores the number of nodes with the highest score. Initially, we set the maximum score to be negative infinity and the count variable to be 0.

As we traverse the tree, we compare the scores of the nodes with the maximum score. If a node has a score greater than the maximum score, we update the maximum score and reset the count variable to 1. If a node has a score equal to the maximum score, we increment the count variable by 1.

Once we have traversed the entire tree, the count variable will contain the number of nodes that have the highest score.

Here is the code implementation in Python:

```
class Node:
def __init__(self, score, left=None, right=None):
self.score = score
self.left = left
self.right = right
def countNodesWithHighestScore(root: Node) -> int:
if root is None:
return 0
max_score = float('-inf')
count = 0
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if visited:
if node.score == max_score:
count += 1
elif node.score > max_score:
max_score = node.score
count = 1
else:
if node.right:
stack.append((node.right, False))
stack.append((node, True))
if node.left:
stack.append((node.left, False))
return count
```

In the above code, we are using the iterative approach of the in-order traversal of the tree using a stack. The stack contains a pair of the node and a boolean value to indicate if the node has been visited. If the node has not been visited, we first push its right child to the stack, then push the node itself with visited flag as true and finally push its left child to the stack. If the node has been visited, we compare its score with the maximum score and update the count variable accordingly.

The time complexity of this algorithm is O(n), where n is the number of nodes in the tree. And the space complexity is also O(n) for the stack used in the iterative approach.

## Count Nodes With The Highest Score Solution Code

`1`