In this lesson, Alvin explores the strategy to solving the following interview problem:
Write a function, tree_sum, that takes in the root of a binary tree that contains number values. The function should return the total sum of all values in the tree.
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
tree_sum(a) # -> 21
a = Node(1)
b = Node(6)
c = Node(0)
d = Node(3)
e = Node(-6)
f = Node(2)
g = Node(2)
h = Node(2)
a.left = b
a.right = c
b.left = d
b.right = e
c.right = f
e.left = g
f.right = h
# 1
# / \
# 6 0
# / \ \
# 3 -6 2
# / \
# 2 2
tree_sum(a) # -> 10
tree_sum(None) # -> 0
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/