Tree
Practice Questions
Implementation in Python
First we are creating a node class where binary tree nodes are represented using the following lines of code.
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
Here left,right, value represents nodes of a binary tree left child and right child where they are empty initially.
Now let us define a binary tree class.Here self is the member of the class and root is the value.
class BinaryTree(object):
def __init__(self,root):
self.root = Node(root)
The above line defines root as node and assigns the value of root to node.
Now we are defining the binary tree with initial value 1and that is the root node.Later we are creating left child node with value 2 and right child node as 3.Also we have defined the values of left child’s child nodes as 4 and 5 and right child’s child nodes as 6 and 7.
# Set up a tree
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
We will get our tree stored in the following format
1
/ \
2 3
/ \ / \
4 5 6 7
Try here>>>