Approach
Depth-first search
For Count Good Nodes in 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
- 47 lines of Python from the credited upstream file count-good-nodes-in-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 TreeNode(object):6 def __init__(self, val=0, left=None, right=None):7 self.val = val8 self.left = left9 self.right = right10 11 12class Solution(object):13 def goodNodes(self, root):14 """15 :type root: TreeNode16 :rtype: int17 """18 result = 019 stk = [(root, root.val)]20 while stk:21 node, curr_max = stk.pop()22 if not node:23 continue24 curr_max = max(curr_max, node.val)25 result += int(curr_max <= node.val)26 stk.append((node.right, curr_max))27 stk.append((node.left, curr_max))28 return result29 30 313233class Solution2(object):34 def goodNodes(self, root):35 """36 :type root: TreeNode37 :rtype: int38 """39 def dfs(node, curr_max):40 if not node:41 return 042 curr_max = max(curr_max, node.val)43 return (int(curr_max <= node.val) +44 dfs(node.left, curr_max) + dfs(node.right, curr_max))45 46 return dfs(root, root.val)47