

That is, we cannot randomly access a node in a tree. Because, all nodes are connected via edges (links) we always start from the root (head) node. Traversal is a process to visit all the nodes of a tree and may print their values too. Accordingly there are different names for these tree traversal methods. Or we can also visit the right sub-tree first and left sub-tree next. As we can clearly see we can start at a node then visit the left sub-tree first and right sub-tree next. The tree can be traversed by deciding on a sequence to visit each node. # Compare the new value with the parent node Finally the PrintTree class is used to print the tree. The insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. To insert into a tree we use the same node class created above and add a insert class to it.

#Complete binary tree code#
When the above code is executed, it produces the following result − We just create a Node class and add assign a value to the node. Below is program to create the root node. We designate one node as root node and then add more nodes as child nodes. We create a tree data structure in python by using the concept os node discussed earlier. It has the following properties −Įvery node other than the root is associated with one parent node.Įach node can have an arbiatry number of chid node. Tree represents the nodes connected by edges. Python Data Structure & Algorithms Useful Resources.Python Data Structure and Algorithms Tutorial.
