In: Computer Science
Python question
Define a function called max_value_length(tree) that takes a Binary Tree object as a parameter and returns an integer that contains the longest character length of all the values in that tree. Use recursion.
For example, the character length of value 123 is 3,
because there are three digits. The character length of value
“Ruru” is 4, because it has four characters. Further, the
max_value_length() function would return 4 if the
only node values in the tree were 123 and “Ruru”,
because 4 is greater than 3.
Note 1: You must use
recursion to answer this question (i.e., not loops).
Note 2: Values in the tree are always treated as
strings.
For example:
Test | Result |
---|---|
binary_tree = create_tree_from_nested_list([7, [2, [14, None, None], [5, None, None]], [9, None, [144, None, None]]]) print(max_value_length(binary_tree)) |
3 |
binary_tree = create_tree_from_nested_list(["Hoiho", ["Kaki", ["Takahe", None, None], None], ["Ruru", None, ["Moa", None, ["Piwaiwaka", None, None]]]]) print(max_value_length(binary_tree)) |
9 |
binary_tree = create_tree_from_nested_list([]) print(max_value_length(binary_tree)) |
0 |
Solution:
binary_tree = ["Hoiho", ["Kaki", ["Takahe", None, None],
None], ["Ruru", None, ["Moa", None, ["Piwaiwaka", None,
None]]]]
max=0 #intializing max variable to "0", this vriable is used to find maximmm size
def my_function(binary_tree):
global max #Accessing max variable out
side this function
if(len(binary_tree) == 0): # if length of input list is empty ,then
return
return
if(index_in_list(binary_tree, 1) and index_in_list(binary_tree, 2)
): # if statement to left and right
childs
my_function(binary_tree[1]) #recursion
with left child
my_function(binary_tree[2]) #recursion
with right child
if binary_tree is not None: #length
will not be calculated for None Type
if max < len(str(binary_tree[0])): # condition to compare and to assign maximum
value
max = len(str(binary_tree[0]))
return max #return maximum value
def index_in_list(a_list, index): #if condition used to check wether the index exist
or not
if a_list is not None: #if index
exists and not None,then return True
return index < len(a_list)
my_function(binary_tree) #calling function
print(max) # finally printing max value
Code in python 3.8.1 IDLE:
Output:
List1: for the list [7, [2, [14, None, None], [5, None, None]], [9, None, [144, None, None]]]
List2: for the list ["Hoiho", ["Kaki", ["Takahe", None, None], None], ["Ruru", None, ["Moa", None, ["Piwaiwaka", None, None]]]]
List3: for the list []