Profile picture
Alvin ZablanFounder at Structy and React Formula | ex-Google

Max Root to Leaf Path Sum Approach

In this lesson, Alvin explores the strategy to solving the following interview problem:

Write a function, max_path_sum, that takes in the root of a binary tree that contains number values. The function should return the maximum sum of any root to leaf path within the tree.

You may assume that the input tree is non-empty.

a = Node(3)
b = Node(11)
c = Node(4)
d = Node(4)
e = Node(-2)
f = Node(1)
a.left = b
a.right = c
b.left = d
b.right = e
c.right = f

#      3
#    /   \
#   11    4
#  / \     \
# 4   -2    1

max_path_sum(a) # -> 18
a = Node(5)
b = Node(11)
c = Node(54)
d = Node(20)
e = Node(15)
f = Node(1)
g = Node(3)
a.left = b
a.right = c
b.left = d
b.right = e
e.left = f
e.right = g

#       5
#     /   \
#    11   54
#  /   \
# 20   15
#      / \
#     1   3

max_path_sum(a) # -> 59

If you need additional support taking these DSA skills and actually applying them, take Alvin's complete data structures and algorithms course on Structy. You can try out the concepts yourself in their interactive code editor and learn advanced DSA patterns like stack exhaustive recursion.

Use this link to get 20% off the entire Structy DSA learning experience.

Follow Alvin on LinkedIn: https://www.linkedin.com/in/alvin-zablan-b73a92117/