A tree data structure consists of:
ALGORITHM preOrder(root)
OUTPUT <-- root.value
if root.left is not NULL
preOrder(root.left)
if root.right is not NULL
preOrder(root.right)
A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.
A Binary Tree node contains following parts.
Implementation
class Node:
def __init__(self, data):
# left child
self.left = None
# right child
self.right = None
# node's value
self.data = data
Traversing a K-ary tree requires a similar approach to the breadth first traversal.
If we traversed this tree Breadth First we should see the output:
Output: A, B, C, D, E, F, G, H
Pseudocode
ALGORITHM breadthFirst(root)
// INPUT <-- root node
// OUTPUT <-- front node of queue to console
Queue breadth <-- new Queue()
breadth.enqueue(root)
while breadth.peek()
node front = breadth.dequeue()
OUTPUT <-- front.value
for child in front.children
breadth.enqueue(child)
Insert − Inserts an element in a tree/create a tree.
Search − Searches an element in a tree.
Preorder Traversal − Traverses a tree in a pre-order manner.
Inorder Traversal − Traverses a tree in an in-order manner.
Postorder Traversal − Traverses a tree in a post-order manner.