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
|
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; } };
|