[LeetCode] Count Dominant Nodes in a Binary Tree

3997. Count Dominant Nodes in a Binary Tree

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int dfs(TreeNode* root, int& res) {
if(!root) return INT_MIN;
int ma = max(dfs(root->left, res), dfs(root->right, res));
if(root->val >= ma) res++;
return max(ma, root->val);
}
public:
int countDominantNodes(TreeNode* root) {
int res = 0;
dfs(root,res);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/count-dominant-nodes-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.