Approach
Depth-first search
For Count Dominant Nodes in a Binary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 55 lines of C++ from the credited upstream file count-dominant-nodes-in-a-binary-tree.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int countDominantNodes(TreeNode* root) {8 const auto& iter_dfs = [&]() {9 using RET = pair<int, int>;10 RET result{};11 vector<tuple<int, TreeNode *, shared_ptr<RET>, shared_ptr<RET>, RET *>> stk = {{1, root, nullptr, nullptr, &result}};12 while (!empty(stk)) {13 const auto [step, u, ret1, ret2, ret] = stk.back(); stk.pop_back();14 if (step == 1) {15 if (!u) {16 continue;17 }18 const auto& ret1 = make_shared<RET>();19 const auto& ret2 = make_shared<RET>();20 stk.emplace_back(2, u, ret1, ret2, ret);21 stk.emplace_back(1, u->right, nullptr, nullptr, ret2.get());22 stk.emplace_back(1, u->left, nullptr, nullptr, ret1.get());23 } else if (step == 2) {24 const auto& mx = max({ret1->second, ret2->second, u->val});25 *ret = pair(ret1->first + ret2->first + (mx == u->val ? 1 : 0), mx);26 }27 }28 return result.first;29 };30 31 return iter_dfs();32 }33};34 35 36373839class Solution2 {40public:41 int countDominantNodes(TreeNode* root) {42 const auto dfs = [](this auto&& dfs, auto u) -> pair<int, int> {43 if (!u) {44 return {0, 0};45 }46 const auto& [cnt1, mx1] = dfs(u->left);47 const auto& [cnt2, mx2] = dfs(u->right);48 const auto& mx = max({mx1, mx2, u->val});49 return {cnt1 + cnt2 + (mx == u->val ? 1 : 0), mx};50 };51 52 return dfs(root).first;53 }54};55