Trees
Trees
A tree is a set of finite set of one or more nodes that shows parent-child
relation such that:
● Root node
● subtrees
Example
Basic Terminologies
Properties of Binary trees
Method 1:
Flag namely used can be used just to indicate whether a memory location is
used or not.
If flag filed used is 0, memory location is not used and indicates absence of
node at that position
Method 2:
One can initialize each location to some value indicating the absence of node
Construction of Binary Tree
14, 2, 8, 0 , 7, 10, 15
Here we do not have any order among elements, so we replace with last element.
Print level order traversal, the last node will be the deepest node
Level order traversal before Deletion of node: 0 1 2 3 4 5 6 7 8 9
In - Order Traversal
In this traversal, the root node is visited first, then its left child and later
its right child.
if(root==NULL) return;
printf(“%d”,root->info);
preorder(root->llink)
preorder(root->rlink);
}
PreOrder - 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
In order Traversal
In this traversal method, the left subtree is visited first, then the root and
later the right sub-tree.
if(root==NULL) return;
Inorder(root->llink);
printf(“%d”,root->info);
Inorder(root->rlink);
}
InOrder - 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
Post order Traversal
In this traversal method, the root node is visited last, hence the name. First we
traverse the left subtree, then the right subtree and finally the root node.
We start from A, and following Post-order traversal, we first visit the left subtree B.
B is also traversed post-order. The process goes on until all the nodes are visited.
The output of post-order traversal of this tree will be −
D→E→B→F→G→C→A
void Postorder(NODE root){
if(root==NULL) return;
Postorder(root->llink);
Postorder(root->rlink);
printf(“%d”,root->info);
}
PostOrder - 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
Binary Search Trees
A node's left child must have value less than its parent's value and
node's right child must have value greater than it's parent value.
Examples of BST
Construction of BST
2) Node to be deleted has only one child: Copy the child to the node and
delete the child
Deletion
Delete node 50
Inorder successor of 50 is 60
So Replace 50 with 60
Traversal
Inorder
Preorder
postorder
Traverse the given BST