Find Value in a Binary Tree

Published by Matt in

An array that represents a Binary Tree is in the following form:

binary_tree = [val , lst_left , lst_right]

When lst_left is the left side of the tree and lst_right is the right side of the tree.

To illustrate:

array1 = [3, [ 8, [ 5, nil, nil], nil], [ 7, nil, nil]]

# array1 represents the following Binary Tree:

                    3
                   / \
                  8   7
                 /\   /\
                5  N N  N
               /\
               N N

# While N represents nil.

Create a function that takes an array that represent a Binary Tree and a value and return true if the value is in the tree and, false otherwise.

Examples

is_val_in_tree(array1, 5) ➞ true

is_val_in_tree(array1, 9) ➞ false

is_val_in_tree(array2, 51) ➞ false

Notes

The tree will contain integers only and will be presented by an array in the specified format.

Watch a quick demo on how Edabit works.