Count Dominant Nodes in a Binary Tree Problem
Description
LeetCode Problem 3997.
You are given the root of a complete binary tree.
A node x is called dominant if its value is equal to the maximum value among all nodes in the subtree rooted at x.
Return the number of dominant nodes in the tree.
Example 1:

Input: root = [5,3,8,2,4,7,1]
Output: 5
Explanation:
- The leaf nodes with values 2, 4, 7, and 1 are dominant.
- The node with value 8 is dominant because its value is the maximum value in its subtree [8, 7, 1].
- Thus, the answer is 5.
Example 2:

Input: root = [1,2,3,1,2]
Output: 4
Explanation:
- The leaf nodes with values 1, 2, and 3 are dominant.
- The node with value 2 whose subtree is [2, 1, 2] is dominant because its value is the maximum value in its subtree.
- Thus, the answer is 4.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 1 <= Node.val <= 10^9- The tree is guaranteed to be a complete binary tree.
Solution
Approach: DFS
A node is dominant when its value equals the maximum of its own subtree. So for each node we only need the maximum of the left subtree and of the right subtree.
Run a post-order DFS. A missing child returns negative infinity (the smallest integer in typed languages). For a node, compute mx = max(leftMax, rightMax, node.val). If mx equals node.val, the node is dominant and the counter goes up by one. Return mx to the parent.
Complexity: time O(n), space O(h) for the recursion, where n is the number of nodes and h is the height. Since the tree is complete, h is O(log n).
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countDominantNodes(self, root: Optional[TreeNode]) -> int:
def dfs(node: Optional[TreeNode]) -> int:
if node is None:
return float("-inf")
l = dfs(node.left)
r = dfs(node.right)
mx = max(l, r, node.val)
if mx == node.val:
nonlocal ans
ans += 1
return mx
ans = 0
dfs(root)
return ans