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
- 52 lines of Python from the credited upstream file count-dominant-nodes-in-a-binary-tree.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks 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(object):6 def countDominantNodes(self, root):7 """8 :type root: Optional[TreeNode]9 :rtype: int10 """11 def iter_dfs():12 ret = [0]*213 stk = [(1, (root, ret))]14 while stk:15 step, args = stk.pop()16 if step == 1:17 u, ret = args18 if u is None:19 continue20 ret1 = [0]*221 ret2 = [0]*222 stk.append((2, (u, ret1, ret2, ret)))23 stk.append((1, (u.right, ret2)))24 stk.append((1, (u.left, ret1)))25 elif step == 2:26 u, ret1, ret2, ret = args27 mx = max(ret1[1], ret2[1], u.val)28 ret[:] = [ret1[0]+ret2[0]+(1 if mx == u.val else 0), mx]29 return ret[0]30 31 return iter_dfs()32 33 34353637class Solution2(object):38 def countDominantNodes(self, root):39 """40 :type root: Optional[TreeNode]41 :rtype: int42 """43 def dfs(u):44 if u is None:45 return [0]*246 cnt1, mx1 = dfs(u.left)47 cnt2, mx2 = dfs(u.right)48 mx = max(mx1, mx2, u.val)49 return [cnt1+cnt2+(1 if mx == u.val else 0), mx]50 51 return dfs(root)[0]52