How I got crazy good at Tree Problems - Step by Step Basic Tree Probs Practice 🌳

238
Oct 16, 2026

How I got crazy good at Tree Problems - Step by Step Basic Tree Probs Practice 🌳

Tree DFS used to confuse me because I was trying to memorize solutions and decide whether everything was "top-down" or "bottom-up."

What finally helped was practicing really basic problems in order and understanding what information is going DOWN and what answer is coming back UP.

How I approach every Tree DFS

1. Do I need information from the parent / path so far?

   YES → pass it DOWN ↓
         dfs(node, state)

   NO → can my children give me what I need?
        get their answers UP ↑


2. Define dfs in ONE sentence:

   dfs(...) returns __________


3. At None/end:
   What happens & what do I return?


4. At leaf:
   Is anything special?


5. At each node:
   What happens?


6. What exactly do I return to my parent?

Most important mental model:

Calls go DOWN ↓
Answers return UP ↑

And the question that helped me the most:

What does dfs(...) return?

"""
        1
      /   \
     2     3
    /     / \
   6     4   5
"""

class TreeNode:
  
  def __init__(self, val=0, left=None, right=None):
    self.val=val
    self.left=left
    self.right=right


# ============================================================
# LEVEL 0: JUST UNDERSTAND TREE TRAVERSAL
# ============================================================


# QUICK Q: Can I simply visit every node and print it?
def printt(root):

  if not root: return

  printt(root.left)
  print(root.val)
  printt(root.right)


# QUICK Q: Can I visit every node and increment one shared counter?
def count(root):

  count=0

  def dfs(root):
    nonlocal count

    if not root: return

    dfs(root.left)
    count+=1
    dfs(root.right)

  dfs(root)
  return count


# QUICK Q: Can I visit every node and add its value to one shared sum?
def sumAll(root):

  sm=0

  def dfs(root):
    nonlocal sm

    if not root: return

    dfs(root.left)
    sm+=root.val
    dfs(root.right)

  dfs(root)
  return sm



# ============================================================
# LEVEL 1: LEARN TO RETURN ANSWERS UP ↑
# ============================================================


# QUICK Q: How many nodes are in THIS subtree?
# No parent info needed → get answers from children ↑
# countNodes(node) returns number of nodes in THIS subtree

def countNodes(root):

  if not root:    # At None/end nodes
    return 0

  left=countNodes(root.left)
  right=countNodes(root.right)

  return left+right+1   # At each node: left + right + myself



# QUICK Q: What is the maximum value in THIS subtree?
# No parent info needed → get answers from children ↑
# maxVal(node) returns max value in THIS subtree

def maxVal(root):

  if not root:
    return float("-inf")   # At None; important if values can be negative

  left=maxVal(root.left)
  right=maxVal(root.right)

  return max(root.val,left,right)   # At each node: max(my val,left,right)



# QUICK Q: Does THIS subtree contain target?
# No parent info needed → return T/F ↑
# dfs(node) returns whether target exists in THIS subtree

def find(root,target):

  def dfs(root):

    if not root: return False   # At None

    if root.val==target:        # At each node
      return True

    return dfs(root.left) or dfs(root.right)

  return dfs(root)



# QUICK Q: Does ANY node in THIS subtree have an even value?
# dfs(node) returns T/F

def hasEven(root):

  if not root: return False   # At None

  if root.val%2==0:           # At each node
    return True

  return hasEven(root.left) or hasEven(root.right)



# QUICK Q: Are ALL nodes in THIS subtree positive?
# dfs(node) returns T/F

def allPos(root):

  if not root:
    return True   # At None: no negative node here, so don't fail

  if root.val<0:
    return False   # At each node: negative → fail

  return allPos(root.left) and allPos(root.right)


# QUICK PATTERN:
#
# ANY condition → left OR right
# ALL condition → left AND right



# ============================================================
# LEETCODE PRACTICE
# ============================================================


# 1) LC 104 - Maximum Depth of Binary Tree
# https://leetcode.com/problems/maximum-depth-of-binary-tree/
#
# QUICK Q: How deep is THIS subtree?
# No parent info needed → children return their depths ↑
# maxDepth(node) returns max depth of THIS subtree

# def maxDepth(self, root: Optional[TreeNode]) -> int:

#     if not root:   # At None/end nodes
#         return 0

#     left=self.maxDepth(root.left)
#     right=self.maxDepth(root.right)

#     return max(left,right)+1   # At each node: best child + myself



# 2) LC 100 - Same Tree
# https://leetcode.com/problems/same-tree/
#
# QUICK Q: Are THESE two subtrees exactly the same?
# No parent info needed → children return T/F ↑
# isSameTree(p,q) returns whether these two subtrees are identical

# def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

#     if not p and not q:   # Both ended together
#         return True

#     if not p or not q:    # Only one ended
#         return False

#     # At each node:
#     # my vals same AND left same AND right same
#     return (
#         p.val==q.val
#         and self.isSameTree(p.left,q.left)
#         and self.isSameTree(p.right,q.right)
#     )



# ============================================================
# LEVEL 2: PASS INFORMATION DOWN ↓
# ============================================================


# QUICK Q: What depth am I currently at?
# Need info from parent → pass level DOWN ↓
# dfs(node,lvl) visits node knowing its current level

def printNodeDepths(root):

  def dfs(root,lvl):

    if not root: return   # At None

    print(root.val,",",lvl)

    lvl+=1   # At each node

    dfs(root.left,lvl)    # OR just pass lvl+1 here
    dfs(root.right,lvl)

  dfs(root,0)



# QUICK Q: What is the sum of the path that got me HERE?
# Need info from parent/path → pass running sum DOWN ↓
# rsum = sum along current root → node path

def printRunningSum(root):

  def dfs(root,rsum):

    if not root: return   # At None

    rsum+=root.val   # At each node

    print(root.val,",",rsum)

    dfs(root.left,rsum)
    dfs(root.right,rsum)

  dfs(root,0)


# IMPORTANT:
#
# Need info about HOW I GOT HERE?
# → pass it DOWN ↓
#
# Need info about WHAT'S BELOW ME?
# → children return answers UP ↑



# ============================================================
# LEVEL 3: PASS VALUE DOWN ↓ + RETURN ANSWER UP ↑
# ============================================================


# QUICK Q: Can ANY root → node path reach target?
#
# Need path info → rsum goes DOWN ↓
# Need answer → T/F comes UP ↑
#
# dfs(node,rsum) returns whether this path/subtree can reach target

def hasSum(root,target):

  def dfs(root,rsum):

    if not root: return False   # At None

    rsum+=root.val   # At each node

    if rsum==target:
      return True

    return dfs(root.left,rsum) or dfs(root.right,rsum)

  return dfs(root,0)


# Mental model:
#
# rsum ↓
#
# T/F ↑



# ============================================================
# LEVEL 4: PATHS + BACKTRACKING
# ============================================================


# QUICK Q: What nodes were on the path that got me HERE?
#
# Need path info from parents → pass path DOWN ↓
# Mutable list → append → explore → pop

def printRootToLeafPaths(root):

  def dfs(root,path):

    if not root:
      return

    path.append(root.val)   # At each node

    if not root.left and not root.right:   # At leaf
      print(path)

    dfs(root.left,path)
    dfs(root.right,path)

    path.pop()   # Undo, same as Subsets logic

  dfs(root,[])


# Backtracking:
#
# append → dfs → pop
#
# Same logic as LC 78 Subsets:
# https://leetcode.com/problems/subsets/



# QUICK Q: How do I SAVE each completed path without later pops changing it?
#
# Same as above, but now we store paths in res
# Need path.copy() because path is one mutable list

def rootToLeafPaths(root):

  res=[]

  def dfs(root,path):

    if not root:
      return

    path.append(root.val)

    if not root.left and not root.right:   # At leaf
      res.append(path.copy())
      # append(path) would save a reference to the SAME list
      # we're still changing/popping
      #
      # path.copy() saves what the path looks like RIGHT NOW

    dfs(root.left,path)
    dfs(root.right,path)

    path.pop()   # Undo

  dfs(root,[])
  return res


# Mental model:
#
# append(path)
# → save reference to SAME list
#
# append(path.copy())
# → save snapshot of list RIGHT NOW



# ============================================================
# LEVEL 5: IMPORTANT PRACTICE FROM HERE!!!
# ============================================================


# Maximum Root-to-Leaf Path Sum
# https://leetcode.com/discuss/post/6632199/maximum-root-to-leaf-path-sum-akamai-by-fby6a/
#
# QUICK Q: What is the best sum from THIS node → a leaf?
#
# Even though this is a path-sum problem:
# Do I need info from parent/path? → NO
# Can children give me what I need? → YES
#
# So get answers from children ↑ (bottom-up)
#
# dfs(node) returns max path sum from THIS node → a leaf

def maxPathSum(root):

  def dfs(root):

    if not root:
      return float("-inf")   # At None; fake path shouldn't beat negative values

    if not root.left and not root.right:   # At leaf
      return root.val

    left=dfs(root.left)
    right=dfs(root.right)

    # At each node:
    # choose best child path + add myself
    return root.val+max(left,right)

  return dfs(root)


# IMPORTANT:
#
# Calls go:
# root → leaf ↓
#
# Answers return:
# leaf → root ↑



# ============================================================
# 3) LC 112 - PATH SUM
# https://leetcode.com/problems/path-sum/
# ============================================================


# QUICK Q: Does ANY complete root → leaf path equal targetSum?
#
# Do I need info from parent/path? → YES
# psum goes DOWN ↓
#
# What does dfs return? → T/F
# T/F comes UP ↑
#
# psum = sum from original root → current node
#
# Previous maxPathSum:
# dfs returned a SUM ↑
#
# This Path Sum:
# psum goes DOWN ↓
# dfs returns T/F UP ↑

class Solution:

    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:

        def dfs(root,psum):   # dfs returns T/F

            if not root:
                return False   # At None

            psum+=root.val   # At each node

            # At leaf, we now have a COMPLETE root → leaf path
            if not root.left and not root.right:
                return targetSum==psum

            left=dfs(root.left,psum)
            right=dfs(root.right,psum)

            # At each node: return if left OR right found a valid path
            return left or right

        return dfs(root,0)



# SAME PATH SUM PROBLEM, ANOTHER WAY:
#
# Instead of:
# start psum=0 → ADD values ↓
#
# We can:
# start remaining=targetSum → SUBTRACT values ↓

# def dfs(node,remaining):

#     if not node:
#         return False

#     remaining-=node.val

#     if not node.left and not node.right:
#         return remaining==0

#     left=dfs(node.left,remaining)
#     right=dfs(node.right,remaining)

#     return left or right

# return dfs(root,targetSum)



# ============================================================
# FINAL TREE DFS CHEAT SHEET
# ============================================================


# STEP 1:
#
# Do I need information from the parent / path so far?
#
# YES → pass it DOWN ↓
#       dfs(node,state)
#
# NO → can children give me what I need?
#      get their answers UP ↑


# STEP 2:
#
# Define dfs in ONE sentence:
#
# dfs(...) returns __________


# STEP 3:
#
# At None/end:
# what happens & what do I return?


# STEP 4:
#
# At leaf:
# is anything special?


# STEP 5:
#
# At each node:
# what happens?


# STEP 6:
#
# What EXACTLY am I returning to my parent?



# ============================================================
# QUICK PATTERN RECOGNITION
# ============================================================


# Need info about HOW I GOT HERE?
# → pass DOWN ↓


# Need info about WHAT'S BELOW ME?
# → return UP ↑


# Need both?
# → pass state DOWN ↓ + return answer UP ↑


# ANY condition?
# → OR


# ALL condition?
# → AND


# Need mutable path?
# → append → dfs → pop


# Saving mutable path?
# → path.copy()


# Calls always go DOWN ↓
# Returned answers come UP ↑


# MOST IMPORTANT:
#
# Don't start by worrying:
# "Is this top-down or bottom-up?"
#
# First ask:
#
# "WHAT DOES dfs(...) RETURN?"



if __name__=="__main__":

  root=TreeNode(
      1,
      TreeNode(2,TreeNode(6)),
      TreeNode(3,TreeNode(4),TreeNode(5))
  )

  root1=TreeNode(
      1,
      TreeNode(2,TreeNode(6)),
      TreeNode(3,TreeNode(-4),TreeNode(5))
  )

  # printt(root)
  # print(count(root))
  # print(sumAll(root))
  # print(countNodes(root))
  # print(maxVal(root))
  # print(find(root,3))
  # print(hasEven(root))
  # print(allPos(root))
  # printNodeDepths(root)
  # printRunningSum(root)
  # print(hasSum(root,8))
  # printRootToLeafPaths(root)
  # print(rootToLeafPaths(root))

  print(maxPathSum(root))

Practice order

LEVEL 0: Traversal
1. Print tree
2. Count using shared variable
3. Sum using shared variable

LEVEL 1: Return answers UP ↑
4. Count Nodes
5. Maximum Value
6. Find Target
7. Has Even
8. All Positive
9. LC 104 Maximum Depth
10. LC 100 Same Tree

LEVEL 2: Pass information DOWN ↓
11. Print Node Depths
12. Running Sum

LEVEL 3: Pass DOWN ↓ + Return UP ↑
13. Root-to-Node Target Sum

LEVEL 4: Mutable path / Backtracking
14. Print Root-to-Leaf Paths
15. Store Root-to-Leaf Paths

LEVEL 5: Put it together
16. Maximum Root-to-Leaf Path Sum
17. LC 112 Path Sum

For me, the biggest change was stopping myself from memorizing whether a problem was "top-down" or "bottom-up."

I first ask:

What does this node need to know, and what does dfs() need to return?

Then:

Need parent/path info → pass it DOWN ↓

Need child/subtree info → get it UP ↑

Need both → do both.

Once I could clearly define dfs() in one sentence, Tree DFS stopped feeling like random recursion.

Part 2: LCA, Balanced Binary Tree, Diameter, Subtree problems and BST recursion.

Comments (3)