Trees
Trees
MICHEAL OGUNDERO
What is a Tree?
A tree is a nonlinear hierarchical data structure that consists of nodes connected by edges.
Each Tree consists of a root node from which we can access each element of the tree.
Why Tree Data Structures?
Other data structures such as arrays, linked list, stack, and queue are linear data structures
that store data sequentially. In order to perform any operation in a linear data structure, the
time complexity increases with the increase in the data size. But, it is not acceptable in
today's computational world.
Different tree data structures allow quicker and easier access to the data as it is a non-linear
data structure.
Tree Terminologies
Node:
A node is an entity that contains a key or value and pointers to its child nodes.
The last nodes of each path are called leaf nodes or external nodes that do not contain a
link/pointer to child nodes.
N.B: The height of a Tree is the height of the root node or the depth of the deepest node.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
Binary Search Tree (BST)
Binary search tree is a data structure that quickly allows us to maintain a sorted list of
numbers.
❖ It is called a binary tree because each tree node has a maximum of two children.
❖ It is called a search tree because it can be used to search for the presence of a number in
O(log(n)) time.
Properties of a Binary Search Tree
The properties that separate a binary search tree from a regular binary tree are:
❖ All nodes of left subtree are less than the root node.
❖ All nodes of right subtree are more than the root node.
N.B: Both subtrees of each node are also BSTs i.e. they have the above two properties.
Regular Binary Tree Vs BST
self.left = None
self.right = None
Insert Operation
def insert(self, value): if newNode.value<temp.value:
temp = temp.right
Search Operation
def minValueNode(currentNode):
while currentNode.left:
currentNode = currentNode.left
return currentNode
Delete a Node
else:
Delete a Node
# If the node has two children,
temp = minValueNode(root.right)
root.key = temp.key
return root
Tree Traversal
Traversing a tree means visiting every node in the tree. You might, for instance, want to add
all the values in the tree or find the largest one. For all these operations, you will need to visit
each node of the tree.
Linear data structures like arrays, stacks, queues, and linked list have only one way to read
the data. But a hierarchical data structure like a tree can be traversed in different ways.
Traverse Preorder
def traverseInOrder(self): [ ]
if self.left:
self.left.traverseInOrder()
print(self.val, end=' ')
if self.right:
self.right.traverseInOrder()
Traverse Postorder
def traversePostOrder(self):
if self.left:
self.left.traversePostOrder()
if self.right:
self.right.traversePostOrder()
print(self.val, end=' ')