Tree
Tree
Tree
By wubie.A
Introduction to trees
• So far we have discussed mainly linear data structures – strings, arrays,
lists, stacks and queues
• The first subset contains a single element called the root of the tree.
• The other two subsets are themselves binary trees called the left and right
sub-trees of the original tree.
• Since a binary tree can contain at most 1 node at level 0 (the root), it
contains at most 2L nodes at level L.
Types of Binary Tree
• Complete binary tree
• Strictly binary tree
• Almost complete binary tree
Strictly binary tree
• If every non-leaf node in a binary tree has nonempty left and right sub-trees,
then such a tree is called a strictly binary tree.
• Or, to put it another way, all of the nodes in a strictly binary tree are of degree z
or two, never degree one.
• All nodes are connected via edges (links) we always start from the root
(head) node.
• Generally we traverse a tree to search or locate given item or key in the tree
or to print all the values it contains.
Traverse tree in Linked list
Pre-order, In-order, Post-order
• Pre-order
<root><left><right>
• In-order
<left><root><right>
• Post-order
<left><right><root>
Pre-order Traversal
• The preorder traversal of a nonempty binary tree is defined as follows:
• Visit the root node
• Traverse the left sub-tree in preorder
• Traverse the right sub-tree in preorder
In-order traversal
• The in-order traversal of a nonempty binary tree is defined as follows:
• Traverse the left sub-tree in in-order
• Visit the root node
• Traverse the right sub-tree in inorder
• But in an n-linked list, there is no way to move through the list other
than one node at a time, permitting only sequential access.
• Search(k, T): Search for key k in the tree T. If k is found in some node of tree
then return true otherwise return false.
• Insert(k, T): Insert a new node with value k in the info field in the tree T such
that the property of BST is maintained.
• Delete(k, T):Delete a node with value k in the info field from the tree T such
that the property of BST is maintained.
• If a new value is less, than the current node's value, go to the left subtree,
else go to the right subtree.
• Following this simple rule, the algorithm reaches a node, which has no left
or right subtree.
• By the moment a place for insertion is found, we can say for sure, that a
new value has no duplicate in the tree.
Algorithm for insertion in BST
• Check, whether value in current node and a new value are equal. If so,
duplicate is found. Otherwise,