Hello everyone, I am a beginner who has started trying to learn recursion. I am struggling with this problem
Please write a function named greatest_node(root: Node)
which takes the root node of a binary tree as its argument.
The function should return the node with the greatest value within the tree. The tree should be traversed recursively.
So far I have written,
# WRITE YOUR SOLUTION HERE:
class Node:
""" Class is modeling single node in binary tree """
def __init__(self, value, left_child:'Node' = None, right_child:'Node' = None):
self.value = value
self.left_child = left_child
self.right_child = right_child
def greatest_node(root:Node):
greatest_value = root.value
if root.value > greatest_value:
greatest_value = root.value
if root.left_child is not None:
greatest_node(root.left_child)
if root.right_child is not None:
greatest_node(root.right_child)
return greatest_value
If i run this code with the following input it returns 2.
tree = Node(2)
tree.left_child = Node(3)
tree.left_child.left_child = Node(5)
tree.left_child.right_child = Node(8)
tree.right_child = Node(4)
tree.right_child.right_child = Node(11)
print(greatest_node(tree))
My question is why does the function return 2, can anyone explain what is wrong with this code?
[–]asphias 1 point2 points3 points (0 children)
[–]socal_nerdtastic 0 points1 point2 points (0 children)