1.
Write a function
build_tree
that returns a tree using the nodes and references implementation that looks like this:

left_child
and right_child
will become references to other instances of the BinaryTree
class. For example, when we insert a new left child into the tree, we create another instance of BinaryTree
and modify self.left_child
in the root to reference the new tree.
BinaryTree
class.
left_child
attribute of the root to refer to this new object. The code for insert_left
is shown in Listing 6.6.3.
def insert_left(self, new_node):
if self.left_child is None:
self.left_child = BinaryTree(new_node)
else:
new_child = BinaryTree(new_node)
new_child.left_child = self.left_child
self.left_child = new_child
else
statement on line 4 of Listing 6.6.3.
insert_right
must consider a symmetric set of cases. There will either be no right child, or we must insert the node between the root and an existing right child. The insertion code is shown in Listing 6.6.4.
def insert_right(self, new_node):
if self.right_child == None:
self.right_child = BinaryTree(new_node)
else:
new_child = BinaryTree(new_node)
new_child.right_child = self.right_child
self.right_child = new_child
def get_root_val(self):
return self.key
def set_root_val(self, new_obj):
self.key = new_obj
def get_left_child(self):
return self.left_child
def get_right_child(self):
return self.right_child
key
, left_child
, and right_child
. Notice that both the left and right children of the root are themselves distinct instances of the BinaryTree
class. As we said in our original recursive definition for a tree, this allows us to treat any child of a binary tree as a binary tree itself.
build_tree
that returns a tree using the nodes and references implementation that looks like this: