15
0 Likes

DSA Crash Course [Part 47] - Tree Min Value Approach

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

Write a function, tree_min_value, that takes in the root of a binary tree that contains number values.

The function should return the minimum value 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

tree_min_value(a) # -> -2
a = Node(5)
b = Node(11)
c = Node(3)
d = Node(4)
e = Node(14)
f = Node(12)
a.left = b
a.right = c
b.left = d
b.right = e
c.right = f

#      5
#    /   \
#   11    3
#  / \     \
# 4   14    12

tree_min_value(a) # -> 3
a = Node(-1)
b = Node(-6)
c = Node(-5)
d = Node(-3)
e = Node(-4)
f = Node(-13)
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    -5
#   /  \     \
# -3   -4   -13
#      /       \
#    -2        -2

tree_min_value(a) # -> -13

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/