Chapter 1: Data structures
However, binary trees can also be created using an array. The first element would contain the root, at index 0. From that point on you would find the index which contains the left and right nodes using the formula: Left index = 2n + 1 Right index = 2n + 2 G D B
J E
H
K
Figure 1.8: A binary tree.
pl
myTree = ['G', 'D', 'J', 'B', 'E', 'H', 'K']
e
Figure 1.8 would be encoded in the array below. To find the index for H, we start at 0. In order to go right we do the calculation 2n + 2 or 2 × 0 + 2 which is 2. From index 2 we go left using the calculation 2n + 1 or 2 × 2 + 1 which is 5. ‘H’ is at position 5.
Adding data to a binary search tree
You can add data to a binary tree by following these simple steps, starting at the root of the tree:
3 4
Compare the data you want to add to the current node. If the new data is less than the node, follow the left pointer, otherwise follow the right pointer. Repeat this until you reach the end of the tree. Update the pointers of the last node to point to the new one.
Sa m
1 2
The Python code below gives you an idea of how this can be done. class node:
def __init__(self, data, parent): self.left = None self.data = data
self.parent = parent self.right = None
def addToTree(self, currentNode, data, parent):
if currentNode == None:
newNode = node(data, parent) else:
if data <= currentNode.data:
addToTree(currentNode.left, data, currentNode) else:
addToTree(currentNode.right, data, currentNode)
© Cambridge University Press 2017 The third party copyright material that appears in this sample may still be pending clearance and may be subject to change.
9