Professional Documents
Culture Documents
Binary Tree
A binary tree consists of a finite set of nodes that is either empty, or consists of one
specially designated node called the root of the binary tree, and the elements of two
disjoint binary trees called the left subtree and right subtree of the root.
Note that the definition above is recursive: we have defined a binary tree in terms of
binary trees. This is appropriate since recursion is an innate characteristic of tree
structures.
The total number of nodes in a complete binary tree of depth d equals 2d+1 – 1. Since all
leaves in such a tree are at level d, the tree contains 2d leaves and, therefore, 2d - 1
internal nodes.
Array Representation
For a complete or almost complete binary tree, storing the binary tree as an array
may be a good choice.
One way to do this is to store the root of the tree in the first element of the array.
Then, for each node in the tree that is stored at subscript k, the node's left child can
be stored at subscript 2k+1 and the right child can be stored at subscript 2k+2. For
example, the almost complete binary tree shown in Diagram 2 can be stored in an
array like so:
However, if this scheme is used to store a binary tree that is not complete or almost
complete, we can end up with a great deal of wasted space in the array.
For example, the following binary tree
Linked Representation
If a binary tree is not complete or almost complete, a better choice for storing it is
to use a linked representation similar to the linked list structures covered earlier in
the semester:
Each tree node has two pointers (usually named left and right). The tree class has
a pointer to the root node of the tree (labeled root in the diagram above).
Any pointer in the tree structure that does not point to a node will normally
contain the value NULL. A linked tree with N nodes will always contain N + 1
null links.
Tree Traversal:
Traversal is a process to visit all the nodes of a tree and may print their values too.
Because, all nodes are connected via edges (links) we always start from the root
(head) node. That is, we cannot randomly access a node in a tree. There are three
ways which we use to traverse a tree −
In-order Traversal
Pre-order Traversal
Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or
to print all the values it contains.
In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later the
right sub-tree. We should always remember that every node may represent a
subtree itself. If a binary tree is traversed in-order, the output will produce sorted
key values in an ascending order.
We start from A, and following in-order traversal, we move to its left subtree B. B
is also traversed in-order. The process goes on until all the nodes are visited. The
output of inorder traversal of this tree will be −
D→B→E→A→F→C→G
Algorithm
Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree and
finally the right subtree.
We start from A, and following pre-order traversal, we first visit A itself and then
move to its left subtree B. B is also traversed pre-order. The process goes on until
all the nodes are visited. The output of pre-order traversal of this tree will be −
A→B→D→E→C→F→G
Algorithm
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.
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
Algorithm
Binary search tree (BST) is a special kind of binary tree where each node contains-
2. Only larger values in its right subtree.
3. Only smaller values in its left subtree
A Binary search tree is shown in the above figure. As the constraint applied on the BST, we can
see that the root node 30 doesn't contain any value greater than or equal to 30 in its left sub-tree
and it also doesn't contain any value less than 30 in its right sub-tree.
Q. Create the binary search tree using the following data elements.
The process of creating BST by using the given elements, is shown in the image below.
Binary Search implementation
Binary Search Tree Operations-
1. Search Operation-
Rules-
Rules-
The insertion of a new key always takes place as the child of some leaf node.
For finding out the suitable leaf node,
Search the key to be inserted from the root node till some leaf node is reached.
Once a leaf node is reached, insert the key as child of that leaf node.
Example-
Consider the following example where key = 40 is inserted in the given BST-
When it comes to deleting a node from the binary search tree, following three cases are possible-
Case-01: Deletion Of A Node Having No Child (Leaf Node)-
Just remove / disconnect the leaf node that is to deleted from the tree.
Example-
Consider the following example where node with value = 20 is deleted from the BST-
Just make the child of the deleting node, the child of its grandparent.
Example-
Consider the following example where node with value = 30 is deleted from the BST-
Case-02: Deletion Of A Node Having Two Children-
A node with two children may be deleted from the BST in the following two ways-
Method-01:
Visit to the right sub tree of the deleting node.
Pluck the least value element called as in order successor.
Replace the deleting element with its in order successor.
Example-
Consider the following example where node with value = 15 is deleted from the BST-
Method-02:
Consider the following example where node with value = 15 is deleted from the BST-
AVL Tree
AVL tree is a height-balanced binary search tree. That means, an AVL tree is also a binary search
tree but it is a balanced tree. A binary tree is said to be balanced if, the difference between the
heights of left and right sub trees of every node in the tree is either -1, 0 or +1. In other words, a
binary tree is said to be balanced if the height of left and right children of every node differ by
either -1, 0 or +1. In an AVL tree, every node maintains an extra information known as balance
factor. The AVL tree was introduced in the year 1962 by G.M. Adelson-Velsky and E.M. Landis.
An AVL tree is defined as follows...
An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node is either -1, 0 or +1.
Balance factor of a node is the difference between the heights of the left and right subtrees of that
node. The balance factor of a node is calculated either height of left sub tree - height of right
sub tree (OR) height of right sub tree - height of left sub tree. In the following explanation, we
calculate as follows...
Balance factor = heightOfLeftSubtree - heightOfRightSubtree
Example of AVL Tree
The above tree is a binary search tree and every node is satisfying balance factor condition. So
this tree is said to be an AVL tree.
Every AVL Tree is a binary search tree but every Binary Search Tree need not be AVL tree.
Rotation is the process of moving nodes either to left or to right to make the tree balanced.
There are four rotations and they are classified into two types.
Single Left Rotation (LL Rotation)
In LL Rotation, every node moves one position to left from the current position. To understand LL Rotation, let us
consider the following insertion operation in AVL Tree...
1. Search
2. Insertion
3. Deletion
Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic.
Step 2 - After insertion, check the Balance Factor of every node.
Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is said to
be imbalanced. In this case, perform suitable Rotation to make it balanced and go for next
operation.
A Red Black Tree is a type of self-balancing binary search tree, in which every node is colored
with a red or black. The red black tree satisfies all the properties of the binary search tree but there
are some additional properties which were added in a Red Black Tree. The height of a Red-Black
tree is O(Logn) where (n is the number of nodes in the tree).
1. Red black tree are useful when we need insertion and deletion relatively frequent.
2. Red-black trees are self-balancing so these operations are guaranteed to be O(logn).
3. They have relatively low constants in a wide variety of scenarios.
To understand insertion operation, let us understand the keys required to define the following
nodes:
When insertion occurs the new node is inserted which is already a balanced tree. But after
inserting many nodes there can be an imbalancing condition occurs which violates the property of
the red black tree. So in this case first we try to recolor first then we go for a rotation.
Case 1)
The imbalancing is concerned with the color of grandparent child i.e. Uncle Node. If uncle node is
red then there are four cases then in this, by doing recoloring imbalancing can be removed.
1) LRr imbalance
In this Red Black Tree violates its property in such a manner that parent and inserted child will be
in a red color at a position of left and right with respect to grandparent. Therefore it is termed as
Left Right imbalance.
2) LLr imbalance
In this red black tree violates its property in such a manner that parent and inserted child will be in
a red color at a position of left and left with respect to grandparent. Therefore it is termed as LEFT
LEFT imbalance.
Removal of LLr imbalance can be done by:
3) RRr imbalance
In this red black tree violates its property in such a manner that parent and inserted child will be in
a red color at a position of right and right with respect to grandparent. Therefore it is termed as
RIGHT RIGHT imbalance.
Removal of RRr imbalance can be done by:
4) RLr imbalance
In this red black tree violates its property in such a manner that parent and inserted child will be in
a red color at a position of right and left with respect to grandparent. Therefore it is termed as
RIGHT LEFT imbalance.
Removal of RLr imbalance can be done by:
Case 2)
The imbalancing can also be occurred when the child of grandparent i.e. uncle node is black. Then
know also four cases will be arises and in this case imbalancing can be removed by using rotation
technique.
1. LR imbalancing
2. LL imbalancing
3. RR imbalancing
4. RL imbalancing
Advantages
Good performance for a splay tree depends on the fact that it is self-optimizing, in that frequently
accessed nodes will move nearer to the root where they can be accessed more quickly. The worst-
case height—though unlikely—is O(n), with the average being O(log n). Having frequently-used
nodes near the root is an advantage for many practical applications (also see Locality of
reference), and is particularly useful for implementing caches and garbage collection algorithms.
Advantages include:
Disadvantages
The most significant disadvantage of splay trees is that the height of a splay tree can be linear. For
example, this will be the case after accessing all n elements in non-decreasing order. Since the
height of a tree corresponds to the worst-case access time, this means that the actual cost of an
operation can be high. However the amortized access cost of this worst case is logarithmic,
O(log n). Also, the expected access cost can be reduced to O(log n) by using a randomized
variant.[3]
The representation of splay trees can change even when they are accessed in a 'read-only' manner
(i.e. by find operations). This complicates the use of such splay trees in a multi-threaded
environment. Specifically, extra management is needed if multiple threads are allowed to
perform find operations concurrently. This also makes them unsuitable for general use in purely
functional programming, although even there they can be used in limited ways to implement
priority queues.
Operations
When a node x is accessed, a splay operation is performed on x to move it to the root. To perform
a splay operation we carry out a sequence of splay steps, each of which movesx closer to the root.
By performing a splay operation on the node of interest after every access, the recently accessed
nodes are kept near the root and the tree remains roughly balanced, so that we achieve the desired
amortized time bounds.
Each particular step depends on three factors:
Zig-zig step: this step is done when p is not the root and x and p are either both right children or
are both left children. The picture below shows the case where x and p are both left children. The
tree is rotated on the edge joining p with its parent g, then rotated on the edge joining x with p.
Note that zig-zig steps are the only thing that differentiate splay trees from the rotate to
root method introduced by Allen and Munro[4] prior to the introduction of splay trees.
Zig-zag step: this step is done when p is not the root and x is a right child and p is a left child or
vice versa. The tree is rotated on the edge between p and x, and then rotated on the resulting edge
between x and g.
Join
Given two trees S and T such that all elements of S are smaller than the elements of T, the
following steps can be used to join them to a single tree:
Splay the largest item in S. Now this item is in the root of S and has a null right child.
Set the right child of the new root to T.
Split
Given a tree and an element x, return two new trees: one containing all elements less than or equal
to x and the other containing all elements greater than x. This can be done in the following way:
Splay x. Now it is in the root so the tree to its left contains all elements smaller than x and the
tree to its right contains all element larger than x.
Split the right subtree from the rest of the tree.
Insertion
To insert a value x into a splay tree:
The node to be deleted is first splayed, i.e. brought to the root of the tree and then deleted.
leaves the tree with two sub trees.
The two sub-trees are then joined using a "join" operation.