Approach
Depth-first search
For Maximum Difference Between Node and Ancestor, 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
- 53 lines of Python from the credited upstream file maximum-difference-between-node-and-ancestor.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
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, x):7 self.val = x8 self.left = None9 self.right = None10 11 1213class Solution(object):14 def maxAncestorDiff(self, root):15 """16 :type root: TreeNode17 :rtype: int18 """19 result = 020 stack = [(root, 0, float("inf"))]21 while stack:22 node, mx, mn = stack.pop()23 if not node:24 continue25 result = max(result, mx-node.val, node.val-mn)26 mx = max(mx, node.val)27 mn = min(mn, node.val)28 stack.append((node.left, mx, mn))29 stack.append((node.right, mx, mn))30 return result31 32 33343536class Solution2(object):37 def maxAncestorDiff(self, root):38 """39 :type root: TreeNode40 :rtype: int41 """42 def maxAncestorDiffHelper(node, mx, mn): 43 if not node:44 return 045 result = max(mx-node.val, node.val-mn)46 mx = max(mx, node.val)47 mn = min(mn, node.val)48 result = max(result, maxAncestorDiffHelper(node.left, mx, mn))49 result = max(result, maxAncestorDiffHelper(node.right, mx, mn))50 return result51 52 return maxAncestorDiffHelper(root, 0, float("inf"))53