0% found this document useful (0 votes)
57 views84 pages

Trees: Balanced Search

The document discusses balanced binary search trees, specifically AVL trees. It defines AVL trees as binary search trees where the heights of the left and right subtrees of every node differ by at most one. It describes how AVL trees maintain this balance property through rotations during insertions and deletions, keeping the worst-case time complexity of operations as O(log n).

Uploaded by

wircexdj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
57 views84 pages

Trees: Balanced Search

The document discusses balanced binary search trees, specifically AVL trees. It defines AVL trees as binary search trees where the heights of the left and right subtrees of every node differ by at most one. It describes how AVL trees maintain this balance property through rotations during insertions and deletions, keeping the worst-case time complexity of operations as O(log n).

Uploaded by

wircexdj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 84

Translated from Turkish to English - www.onlinedoctranslator.

com

Balanced Search
trees
(Balanced Search Tree)
•AVL tree
•2-3 and 2-3-4 trees
•splay tree
•Red Black Tree
•B-tree

one
2nd

BALANCED TREE

-A balanced tree is a tree shape that reflects its development


homogeneously to all its branches; By definition, the
difference between the heights of the subtrees attached to
any node is, as seen in figures a) and b),at most 1 (one)
should be. Overgrowth of a branch destabilizes the tree and
deviates from the complexity calculations and execution time
relations calculated on the tree. Therefore, the most
important benefit of the tree data model starts to disappear.
- In the statistical studies, it has been observed that the tree
is balanced or shows little deviation in the case of random
data for the formation of the tree [HIBBARD-1962].
3

BALANCED TREE
4

Height Balanced Trees


- There are many BST balancing algorithms
to perform BST operations in less time.
Some of those;
- Adelson-Velskii and Landis (AVL) trees (1962)
- Splay trees (1978)
- B-tree and other versatile search trees (1972)
- Red-Black trees (1972)
- Also known as Symmetric Binary B-Trees
AVL TREE

5
6

AVL TREES

- AVL( GM Adelson-Velskii and EM LandisA binary search tree


constructed according to the ) method, binary AVL search tree
is called.

- The property of the AVL tree is that the height difference between the right
subtree and the left subtree is at most one node that is. This rule applies to
all nodes of the tree.

- Fornormal binary search trees, the insertion and deletion


algorithms cause the tree to become malformed on binary
AVL trees, that is, to destabilize the tree.
7

AVL Trees: Definition


one. The entire empty tree is an AVL tree.

2nd. If T is not empty TL and TR A binary search tree


with left and right subtrees in the form of a T is
called an AVL tree if and only if the following
conditions are met.
one. TL and TR If AVL trees are
2nd. hL and hR TL and TR including the heights of
|hL – hR| It has to be <= 1.

hL+1 or hL-one
hL
TL TR
8

AVL Trees
- AVL trees are balanced binary search trees.
- left = height(left subtree), and
sagh=height(right subtree) if HUNTINGTree

- Equilibrium factor at a node = solh - sagh 60

- In AVL trees, the balance factor is only -1, 0, 1 it one


4 7
- one

could be.

- if equal 0 0 one 9 0
- If left saz one
red numbers balance
- If more than right - one
is a factor.

- The difference between the heights of the left and


right subtrees of each node can be at most 1.
9
AVL Trees: Examples

60 6 - one
6 0
one 4 0 4
one5 7 - one 10 2nd 9 one

0 4 0 one 8 0 0 one 5 8 0
9 0
07 9 0
AVL Tree AVL Tree
Not an AVL Tree

6 6 0
6 one
- one

one4 9 2nd 04
2nd 4 7 - 2nd

90
0 one 7 one3 8 - one

0 one 5 0
- one

80 0 one 9 0

Not an AVL Tree AVL Tree Not an AVL Tree

The red numbers are the balance factor.


10

AVL Tree: Implementation

- For the implementation of the AVL tree, the


height of each x node is recorded.
- balance factor of x = height of left
subtree of x – height of right subtree of x
- In AVL trees, “bf” can only take the values {-1, 0,
1}. class i'm hunting

x {
int value;
key
left int height;
right
height i'm hunting left;
i'm hunting right;
}
11th

AVL TREES

- Worstrunning times of functions in normal


binary search trees Tw = O(n) is This creates a
very bad result since it is linear time.

- This
bad uptime is eliminated by creating an
AVL tree data model.

- For AVL trees Tw = O (log n)is .


12

AVL Trees
HUNTINGTree

- Height of an AVL Height = O(log n)


60
tree with N nodes
is always O(log n). one 5
7
- one

- So how?
04
9 0

red numbers balance


is a factor.
13

AVL Trees: Lucky and Unlucky

- Lucky:
- call duration O(h) = O(log n)
- unlucky
- Adding and deleting operations can cause the tree to
become unstable.

0 Add 3
6 6 one

one
5 7 7
- one
2nd 5 - one

0 4 0 one 4
9 9 0

03
AVL Tree
No longer an AVL tree
14

Maintaining Balance in the AVL Tree

- Problem: In some cases, the insertion


process in regions that are root with
6 one
respect to the insertion point may cause
the balance factor to be 2 or -2. 2nd 5 7 - one

4
one 9 0
- Idea: After adding the new node
one. Get to the root by correcting the balance factor.
0 3

2nd. If the node's balance factor is 2 or -2, the


tree is corrected by rotating it on that
node.
15

Balancing: Example
Add 3 rotation
60 6 2nd 6 0
one 5 7 - one
2nd
5 7 - one
0 4 7 - one

0 4 9 0 one4 9 0 0 3 5 0 9 0

AVL 0 3
AVL
Not AVL

- After adding the new node


one. Get to the root by correcting the balance factor.
2nd. If the node's balance factor is 2 or -2, the tree is
corrected by rotating it on that node.
16

AVL Tree - Add (1)


P Pivot: bf, 2nd or -2nd
P

L R

A B NS D

- P Considering that the knot is the knot that upsets


the balance.
– P pivot is called a node.
– It is the first node where bf is 2 or -2 as it moves towards
the root after addition.
17

AVL Tree - Add (2)


P Pivot: bf, 2nd or -2nd
P
L R

A B NS D
- There are 4 different situations:

– External Situation (requiring single rotation):


one. When added to the left of the left subtree of P (LL Imbalance).
2nd. When added to the right of the right subtree of P (RR Imbalance)

− Internal Status (Requires 2 rotations):


3. When added to the right of the left subtree of P (RL Imbalance)
4. When added to the left of the right subtree of P(LR Imbalance)
18

LL Imbalance & Correction

L
rotation
2nd P
P
0 or 1 L R A
R
B
A B NS D
NS D
tree after insertion
Tree after LL Correction

- LL Imbalance: When we add to the left of the left subtree of P


(subtree A)
– P of bf NS 2nd
– L of bf NS 0 or 1
- Correction: Single rotation around P to the right.
19

LL Example of Correcting Imbalance (1)

one Add(2) one one Turn one


10 10 10 10

one4 20 0 4
one 20 0 2nd 4 0 20 0 0 3 20 0

0 3 0 3 3
one 0 2nd 4 0
at the beginning
0 2nd 0 2nd LL Fix
AVL Tree
your pivot after it's done
After adding 2 determination AVL tree
state of the tree
The type of imbalance
balance factor determination
straighten to root
advance
• LL Imbalance:
– P(4)'Fame bf NS 2nd
– L(3)'Fame bf NS 0 or 1
20

LL Example of Correcting Imbalance (2)


one Add(2) Turn
10 one 10
2nd 10
0 4

0 4 20 0 0 4 4
one 20 0
20 0 3 10 0
one

0 3 5 0 3
one 50
03 50 0 2nd 5 0 20 0
at the beginning
0 2nd 0 2nd
AVL Tree your pivot LL Fix
After adding 2 determination after it's done
state of the tree AVL tree
The type of imbalance
balance factor determination
root by straightening
• LL Imbalance:
move forward
– P(4)'Fame bfNS 2nd
– L(3)'Fame bfNS 0 or 1
21

RR Imbalance & Correction


Turn R
P -2nd
P
L R 0 or -1 D
L
NS
A B NS D
After adding A B
After RR Correction
• RR Imbalance: When added to the right of P's right
subtree (added to D subtree)
– P - bf = -2nd
- R - bf = 0 or -1
– Correction: Single rotation around P to the left
22

RR Example of Correcting Imbalance (1)


10 -one Add(40) 10 -one
Turn 10 - one
10 -one

0 4 20 -one 0 4 20 -one 0 4 20 -2nd 04 30 0

30 0 30 0 30 -one 0 20 40 0
at the beginning
AVL Tree 40 0 40 0 RR Correction
after it's done
After adding 40 your pivot
AVL tree
state of the tree determination

The type of imbalance


balance factor determination
straighten to root
advance
• RR Imbalance:
– P(20) - bf = -2nd
– R(30) - bf = 0 or -1
23

RR Example of Correcting Imbalance (2)


10 -one Add(40) 10 -2nd Turn 20 0

0 4 20 0 0 4 20 -one 0 10 30 -one

0 15 30 0 0 15 30 -one 04 15 0 40 0

at the beginning
40 0
AVL Tree
After adding 40 RR Correction
state of the tree after it's done
AVL tree
Proceed to the root by correcting the The type of imbalance
balance factor and set 10 as the pivot determination
set
• RR Imbalance:
– P(10) - bf = -2nd
– R(20) - bf = 0 or -1
24

LR Imbalance & Correction

1. Rotation
2nd
P P 2. Rotation
LR

L 2nd R LR 2nd R
- one
L P
one L
LR R
A NS D B2 NS D A B1 B2
A
B1 B2 B1
NS D
tree after insertion 1. Tree after rotation After LR Fix
• LR Imbalance: When added to the right of the left subtree of P (to the LR tree)
– P - bf = 2nd
- L - bf = -one
– Correction: Rotate around L & P 2 times
25

LR Example of Correcting Imbalance


2nd
Add(5) Turn 0 7
one 10 10
2nd
0 4 20 0 - one 4 20 0 04 10 -one

one
0 3 70 03 7 one 03 5 0 20 0

at the beginning 5 0 After LR Fix


AVL Tree state of the tree
After adding 2
balance factor state of the tree
straighten to root • LR Imbalance:
advance and pivot 10
The type of imbalance – P(10) - bf = 2nd
set as determination – L(4) - bf = -one
26

RL Imbalance & Correction

1. Rotation 2. Rotation RL
P - 2nd P - 2nd

2nd R one P R
2nd RL
L L
R L
one
RL
A A C1 C1 C2 D
B D B
A B
C1 C2 C2 D
tree after insertion 1. After rotation After RL Fix

• RL Imbalance: Added to the left of P's right subtree (to


RL subtree)
– P - bf = -2nd
- R - bf = one
– Correction: Rotation around R&P 2 times.
27

RL Example of Correcting Imbalance


Add(17) - 2nd 10 Turn 15 0
- one
10
2nd
0 4 20 one one
10 20 0
0 4 20 0
one
0 15 30 0 - one 15 30 0 04 0 17 30 0

at the beginning 17 0
RL Fix
AVL Tree
after adding 17 after it's done
state of the tree AVL tree
balance factor
straighten to root The type of imbalance
advance and pivot 10 determination
set as
• RL Imbalance:
– P(10) - bf = -2nd
– R(20) - bf = one
28

AVL TREES

- Some Functions of AVL Trees Written in C Codes

- Function 1. Node Definition for AVL Tree


-
- public class AvlAgac {public
- long data;
- public AvlAgac left;
- public AvlAgac right;
- int height=0;
- }
29

AVL TREES

- Function 2. Function Returning the Height of an AVL


Node
-
- intheight (AvlAgac p)
- if (p == null)
- return -one;
- else
- {
- return = p.height;
- }
30

AVL TREES
- Function 3. Add Function for AVL Tree
- public AvlAgac insert(AvlAgac p, int x) {
- if (p == null)
-{ p = new AvlAgac(); p.data = x; }
- else
-{ if (x <p.data)
- {
- p.left = insert(p.left, x);if (height(p.left)-
- height(p.right) == 2)if (x < p.left.data)
-
- p = singlerotateright(p);
- else p = doublerotateright(p);
- }
31

AVL TREES
- else if (x > p.data)
- { p.right = insert(p.right, x);
- if (height(p.left) - height(p.right) == -2)if (x >
- p.right.data)
- p = singlerotateleft(p);
- else p = doublerotateleft(p); }
-
- p.height = max(height(p.left), height(p.right)) + 1; return p;
-
- }
- int max(int a, int b)
- { if (a > b) return a;
- else return b;
- }
32

AVL TREES

- Function 4. Single right rotation (LL) Function for AVL Tree

- AvlAgac singlerotateleft(AvlAgac p) {
-
- AvlAgac lc = p.left;
- p.left = lc.right;
- lc.right = p;
- p.height = max(height(p.left), height(p.right)) + 1; lc.height =
- max(height(lc.left), lc.height) + 1;return lc;
-
- }
33

AVL TREES

- Function 5. LR double rotation for AVL Tree

- AvlAgacdoublerotateright(AvlAgac p)

- {
- p.left = singlerotateleft(p.left);return
- singlerotateright(p); }
-
34

AVL TREES

- Function 6. Right single rotation (RR) Function for AVL Tree

- AvlAgac singlerotateleft(AvlAgac p) {
-
- AvlAgac rc = p.right;
- p.right = rc.left;
- rc.left = p;
- p.height = max(height(p.left), height(p.right))+1; rc.height =
- max(height(rc.right), rc.height)+ 1;return rc;
-
- }
35

AVL TREES

- Function 7. RL double rotation for AVL Tree

- AvlAgacdoublerotateleft(AvlAgac p)

- {
- p.right = singlerotateright(p.right);return
- singlerotateleft(p); }
-
36

AVL TREES

- Sample:

- 46, added
37

AVL TREES

- Sample:

-
-

- Balanced AVL tree


38

AVL TREES
- Example:Create a 1,2,3,4,5,6,7,8,9,10 tree and balance it
step by step.
39

AVL TREES - Deletion


- The deletion operation is similar to the insert operation.
- While
performing the deletion in AVL trees, especially the deletion of the
nodes with children appears in different structures. The aim is to first
provide a knot that will not disturb the balance.
- Theoldest child on the Left or the youngest child on the Right becomes
the new node. The important thing is to restore the balancing process
after the deletion.. More than one rotation can be done during this
process.
- Rule1: If the deleted node is a leaf, no problem, just do it if
balancing is required.
- Rule2: If the deleted node is a node with children, take either the largest
child on the left or the youngest child on the right. During this process,
more than one rotation can be done for balancing.
40

Deletion Example (1)

one Delete(20)
Turn
10 one 10 2nd
10 4 - one

0 4 20 0 04 0 4 0 3 10 one

0 3 5 0 0 3 50 0 3 5 0 0 5

at the beginning 20 after deletion 10 as pivot From LL Fix


AVL Tree state of the tree determination Then AVL Tree

balance factor The type of imbalance


straighten to root determination

advance
LL Imbalance:
– P(10)'Fame bfNS 2nd

– L(4)'Fame bfNS 0 or 1
41

Deletion Example (2)


one Delete(20)
one Turn
10 10 2nd
10 5 0

4 2nd
- one
20 0 - one 4 - one 4 0 4 10 0
one
5 0 50 From LR Fix
5 0
then AVL Tree
at the beginning 20 after deletion 10 as pivot
AVL Tree state of the tree determination

balance factor The type of imbalance


straighten to root determination

advance

LR Imbalance:
– P(10) - bf = 2nd
– L(4) - bf = -one
42

Deletion Example (3)


one
15
one
10 Delete(10)

5 20
- one
one
5 20
- one
one

3
one 7 30 -one
7 0 15
- one
one 3 - one 30 -one

2nd 0 4
one 0 8 0 40
2nd 0 4
one 0 8 0 40
0 one
0 one 10 after deletion
Initial AVL Tree 10 and 15(smallest element
in right subtree) swapped
and 15 deleted.

balance factor
root by straightening
move forward
43

Deletion Example (3)


one Turn one
15
15

5
one 20
- 2nd
5
one 30 0

one 3 7 30 -one 3
one - one 7 20 0 40 0
- one

2nd 0 4
one 2nd 0 4
one 0 8
0 8 0 40

0 one choosing 20 as pivot 0 one


RR Imbalance
after corrected
The type of imbalance
set AVL tree above
is it?
RR Imbalance:
balance factor
– P(20) - bf = -2nd
straighten to root
– R(30) - bf = 0 or -1 move forward.
44

Deletion Example (3)


2nd
15 Turn 0 5

one 5 30 0 one 3 15 0

one 3 -one 7 20 0 40 0 one 2nd 04 7 - one 30 0


one 2nd 0408 0 one
08 20 0 40 0

0 one
Setting 15 as the pivot Adjusted AVL tree

of imbalance
set type
LL Imbalance:
– P(15) - bf = 2nd
– L(5) - bf = 0 or 1
45

Deletion Example – Rule 2

- 19 deleted (The largest node on the left or the smallest node on the right is made the root.

or
46

Deletion Example – Rule 1-2


- Sample: Delete in order; 58 ,7, 40,10,14 (Left
biggest node will be taken)

58

-7 40 10

- 14
47

Deletion Example – Rule 1-2


- Sample: Delete in order; 58 , 7, 40,10,14 (The smallest on the Right in deletion
node will be taken)

58,7,40

- 10 14
48

Deletion Example
- Sample: Add 7 to the tree and balance it.

- Delete the value 20 from the tree (The smallest node on the right will be taken)
49

AVL -Search (Find)

- Since the AVL tree is a type of Binary Search Tree (BST),


the search algorithm is the same as BST.

- It is guaranteed to work in O(logN).


50

AVL Trees – Summary

- Advantages of AVL Trees


one. Because the AVL tree is always balanced, Search/Add/Delete
is done in O(logN).
2nd. The correction process does not affect the complexity of the algorithms.

- Disadvantages of AVL Trees:


one. Extra space is required for the balancing factor.
2nd. It performs as well as AVL trees in semi-balanced trees,
and balance factor is not used in such algorithms.
- Splay trees
51

Homework

- Application : Make the S,E,L,I,M, K,A,Ç,T,I AVL tree.


- Answer: The value of the root node is L
- Leaf node values: A,I,K,M,T
- DSW method (Recreate)
-- Adjusts the heights by rebuilding the tree
- -Obtains backbone from tree and rebuilds tree
- - Developed by Colin Day, Quentin F. Stout and Bette
L.Warren
- Self-Adjusting Trees (Priority)
-- Constantly organizes the tree according to the frequency of use

-- Approaches root when accessing each element.


- The parts indicated in red will be prepared and delivered as a word
document together with the program as soon as possible.
SPLAY TREE

•AVL tree
•2-3 and 2-3-4 trees
•splay tree
•Red Black Tree
•B-tree

52
53

Splay Trees

- Splay trees are one of the binary search tree structures.


- It is not always balanced.
- It tries to balance the search and insert
operations so that future operations run faster.

- It is intuitive.
- If X has been accessed once, it will be accessed once more.
- After X is reached, the "splaying" operation is performed.
- X moves to the root.
54

Sample
- Here, besides the tree being balanced, 12 can be
accessed in O(1) time.
- Active (recently accessed) active when moving nodes
towards rootnodes that are not rooted out.

Root Root

15 After find(12) 12
2nd
6 18 Splay main idea: 6 15
using rotation
one
3 12 12Bring the root . 3 9 14 18

9 14
after 12 calls
starting tree
55

Splay Tree Terminology


- Let X be a non-root node. (with family)
- Let P be the family node of X.
- Let G be the parent node of X.
-G and x Considering the path between:
- Every right move operation "zigIt's called the 'process.
- Every left move operation "zagIt's called the 'process.
-A total of 6 different situations can occur:

G G G G

P P P P P P

x x x x x x
1. zig 2. zig-zig 3. zig-zag 4. zag-zig 5. zag-zag 6. zag
56

Splay Woodworking
-When X is reached, one of 6 rotations is
executed:
- Single Rotation (X has P but not G)
- zig, zag

- Double Rotation (X has both P and G)


- zig-zig, zig-zag
- zag-zig, zag-zag
57

Splay Trees: Zig Process


- The “zig” operation is the only rotation operation as in the
AVL tree.
- For example, considering that the element accessed is 6.

15
6
Zig-Right
6 18 15
3

3 12 12 18

- The “Zig-Right” operation moves 6 to the root.

- In the next operation, 6 is also accessible in O(1). It is similar


- to the right rotation operation in the AVL tree.
58

Splay Trees: The Zig-Zig Process


- The “Zig-Zig” operation involves 2 rotations of the same type. For
- example, considering that the accessed element is 3.

15 6 3
Zig-Right Zig-Right

6 18 one 6
3 15
4 15
3 12 one 4 12 18

one 4 12 18

- “It has been moved to 3 roots with the zig-zig process.


- Note: family - ancestor rotation between is done first.
59

Splay Trees: Zag Process

- The “zag” operation is the only rotation operation as in the AVL tree. For

- example, considering that the element accessed is 15. “The zag-sol

- operation moves 15 to the root.

- In the next operation, 15 is also accessible in O(1). It is

- similar to the left rotation operation in the AVL tree.

6 15

Zag-Left
3 15 6 18

12 18 3 12
60

Splay Trees: Zag-Zag Process


- The “Zag-Zag” operation includes 2 rotations of the same type.
- For example, considering that the element accessed is 30. With
- the "zag-zag" operation, it has been moved to 30 roots.Note:
- family - ancestor rotation between is done first.

15 Zag-Left 20 Zag-Left 30
15 30
6 20 20 40
6 17 25 40 15 25
17 30

6 17
25 40
61

Splay Trees: Zig-Zag state


- In the zig-zag case, X is the right child of P and the ancestor of G. The
- “Zig-Zag” state includes 2 different types of rotation.
- For example, considering that the element accessed is 12.

- With the "zig-zag" process, it has been moved to 12 roots.

- in the AVL tree LR imbalanceIt is the same as the operations used to


correct the . (first left turn, then right turn)

15 Zag-Left 15 Zig-Right 12

6 18 12 18 6 15

12 3 10 14 18
3 6 14

10 14 3 10
62

Splay Trees: Zag-Zig state


- In the case of Zag-Zig, X is the left child of P and the ancestor
of G.
- The “Zag-Zig” state includes 2 different types of rotation. For
- example, considering that the element accessed is 17. With the
- zag-zig” operation, it has been moved to 17 roots.
- in the AVL tree RL imbalanceIt is the same as the operations used to
correct the (first right turn, then left turn)
15 15 Zag-Left 17
Zig-Right

6 20 6 15 20
17
6 16 18 30
17 30 16 20

18 30
16 18
63

Splay Tree Example: When 40 is Reached

80
80 40
70 85
70 85 30 70

60 75 50 80
40 75
50 65 45 60 75 85
30 50
55 65
40 55 45 60

55 65
30 45 zig-zig
zig-zig
(a) (b) (NS)
64

Splay Tree Example: When 60 is Reached

40 40
60
30 70 30 60 40 70

50 70
50 80 30 50 65 80

45 60 75 85 45 55 65 80 85
45 55 75

55 65 75 85

zig-zag
zag
(a) (b) (NS)
65

Splashing During Other Operations

- Splaying can be applied not only after Search but also after
value operations such as Add/Delete.

- Add X: Move X to root after X has been added to the leaf node (BST
operation).

- Delete X: Search X and move it to root. Delete the X in the root and move
the largest element in the left subtree or the smallest element in the right
root to the root.

- Find X: If X is not found, move the leaf node where the search
ended to the root.
66

Splay Trees – Summary

- With the splaying process, the tree generally remains in balance.

- Analysis result: The running time of k operations on


an N-dimensional Splay tree is O(k log N). So the
runtime for a single process is O(log N).

- Even if the depth of the elements to be accessed is very large, the


duration of the search operations will become shorter after a while.
Because each search operation ensures the balancing of the tree.
67

Homework

- A,V,L, A,Ğ,A,C,I,N,A,E,K,L,E,M,E elements are added


to an empty AVL tree in order.

- Show by drawing the trees that are formed when


each element is added.
68

Homework

- S,P,L,A,Y,A,G,A,C,I,N,A,E,K,L,E,M,E elements are


added to an empty Splay tree in order.
- Show the resulting tree by drawing.

- After accessing "S" and then "A" first, show


the structure of the tree by drawing.
- Make the C program of the splay tree given
below with Java or C#.
69

Example Program C++


- # include<stdio.h>
- # include<malloc.h>
- # include<stdlib.h>
- struct node
- { int data;
- struct node *parent;
- struct node *left;
- struct node *right;
- };
- int data_print(struct node *x);
- struct node *rightrotation(struct node *p,struct node *root);
- struct node *leftrotation(struct node *p,struct node *root); void
- splay(struct node *x, struct node *root);
- struct node *insert(struct node *p,int value);
- struct node *inorder(struct node *p);
- struct node *delete(struct node *p,int value);
- struct node *successor(struct node *x); struct
- node *lookup(struct node *p,int value);
70

Example Program C++


- void splay (struct node *x, struct node *root)
- { struct node *p,*g;
- /*check if node x is the root
- node*/ if(x==root) return;
- /*Performs Zig step*/
- else if(x->parent==root) {
-
- if(x==x->parent->left) root=rightrotation(root,root);
- else root=leftrotation(root,root);
- }
- else
- { p=x->parent; /*now points to parent of x*/ g=p->parent; /*now
- points to parent of x's parent*/ /*Performs the Zig-zig step when x
- is left and x's parent is left*/ if(x==p->left&&p==g->left)
-
- { root=rightrotation(g,root);
- root=rightrotation(p,root);
- }
71

Example Program C++


- /*Performs the Zig-zig step when x is right and x's parent is right*/
- else if(x==p->right&&p==g->right)
- { root=leftrotation(g,root);
- root=leftrotation(p,root);
- }
- /*Performs the Zig-zag step when x's is right and x's parent is left*/
- else if(x==p->right&&p==g->left)
- { root=leftrotation(p,root);
- root=rightrotation(g,root);
- }
- /*Performs the Zig-zag step when x's is left and x's parent is right*/
- else if(x==p->left&&p==g->right)
- { root=rightrotation(p,root);
- root=leftrotation(g,root);
- }
- splay(x, root);
- }
- }
72

Example Program C++


- struct node *rightrotation(struct node *p,struct node *root)
- { struct node *x;
- x = p->left;
- p->left = x->right;
- if (x->right!=NULL) x->right->parent = p; x-
- >right = p;
- if (p->parent!=NULL)
- if(p==p->parent->right) p->parent->right=x;
- else
- p->parent->left=x;
- x->parent = p->parent;
- p->parent = x;
- if (p==root) return x;
- else return root;
- }
73

Example Program C++


- struct node *leftrotation(struct node *p,struct node *root)
- { struct node *x;
- x = p->right;
- p->right = x->left;
- if (x->left!=NULL) x->left->parent = p; x-
- >left = p;
- if (p->parent!=NULL)
- if (p==p->parent->left) p->parent->left=x;
- else
- p->parent->right=x;
- x->parent = p->parent;
- p->parent = x;
- if(p==root)
- return x;
- else
- return root;
- }
74

Example Program C++


- struct node *insert(struct node *p,int value)
- { struct node *temp1,*temp2,*par,*x; if(p ==
- NULL)
- { p=(struct node *)malloc(sizeof(struct node));
- if(p != NULL)
- { p->data = value; p-
- >parent = NULL;
- p->left = NULL;
- p->right = NULL;
- }
- else
- { printf("No memory is allocated\n");
- exit(0);
- }
- return(p);
- } //the case 2 says that we must splay newly inserted node to root
75

Example Program C++


- else { temp2 = p;
- while(temp2 != NULL)
- { temp1 = temp2; if(temp2->data
- > value) else if(temp2->data temp2 = temp2->left;
- < value) else temp2 = temp2->right;
-
- if(temp2->data == value) return temp2;
- }
- if(temp1->data > value) { par = temp1;//temp1 having the parent
- address,so that's it temp1->left = (struct node
- *)malloc(sizeof(struct node)); temp1= temp1->left;
-
- if(temp1 != NULL)
- { temp1->data = value;
- temp1->parent = par;//store the parent address.
- temp1->left = NULL; temp1->right = NULL; }
- else { printf("No memory is allocated\n"); exit(0); }
- }
76

Example Program C++


- else
- { par = temp1; // temp1 having the parent node address.
- temp1->right = (struct node *)malloc(sizeof(struct node));
- temp1 = temp1->right;
- if(temp1 != NULL)
- { temp1->data = value;
- temp1->parent = par;//store the parent address
- temp1->left = NULL; temp1->right = NULL;
- }
- else { printf("No memory is allocated\n"); exit(0); }
- }
- }
- splay(temp1,p);//temp1 will be new root after splaying
- return (temp1);
- }
77

Example Program C++


- struct node *inorder(struct node *p) {
-
- if(p != NULL)
- {
- inorder(p->left);
- printf("CURRENT %d\t",p->data); printf("LEFT
- %d\t",data_print(p->left)); printf("PARENT
- %d\t",data_print(p->parent)); printf("RIGHT
- %d\t\n",data_print(p->right)); inorder(p->right);
-
- }
- }
78

Example Program C++


- struct node *delete(struct node *p,int value)
- { struct node *x,*y,*p1; struct node *root; struct node *s; root = p;
- x = lookup(p,value);
- if(x->data == value)
- { //if the deleted element is leaf
- if((x->left == NULL) && (x->right == NULL))
- { y = x->parent;
- if(x ==(x->parent->right)) y->right = NULL;
- else y->left = NULL; free(x);
- }
- //if deleted element having left child only else
- if((x->left != NULL) &&(x->right == NULL)) { if(x
- == (x->parent->left))
- { y = x->parent; x->left->parent = y; y->left = x->left; free(x); }
- else { y = x->parent; x->left->parent = y; y->right = x->left; free(x); }
- }
79

Example Program C++


- //if deleted element having right child only else
- if((x->left == NULL) && (x->right != NULL))
- { if(x == (x->parent->left)) { y = x->parent; x->right->parent = y; y->left = x->right; free(x); }
- else { y = x->parent; x->right->parent = y; y->right = x->right; free(x); } }
-
- //if the deleted element having two children
- else if((x->left != NULL) && (x->right != NULL))
- { if(x == (x->parent->left))
- { s = successor(x);
- if(s != x->right)
- { y = s->parent;
- if(s->right != NULL)
- { s->right->parent = y; y->left = s->right; }
- else y->left = NULL;
- s->parent = x->parent; x->right->parent = s;
- x->left->parent = s; s->right = x->right;
- s->left = x->left; x->parent->left = s;
- }
80

Example Program C++


- else { y = s; s->parent = x->parent;
- x->left->parent = s; s->left = x->left; x->parent->left = s; }
- free(x); }
- else if(x == (x->parent->right))
- { s = successor(x);
- if(s != x->right)
- { y = s->parent;
- if(s->right != NULL) {s->right->parent = y; y->left = s->right; } else
- y->left = NULL;
- s->parent = x->parent; x->right->parent = s; x-
- >left->parent = s; s->right = x->right; s->left =
- x->left; x->parent->right = s; }
- else { y = s; s->parent = x->parent; x->left->parent = s;
- s->left = x->left; x->parent->right = s; }
- free(x);
- }} splay(y,root);
- } else { splay(x,root); }
- }
81

Example Program C++


- struct node *successor(struct node *x)
- { struct node *temp,*temp2; temp=temp2=x->right;
- while(temp != NULL) { temp2 = temp; temp = temp->left; }
- return temp2; }
- //p is a root element of the tree
- struct node *lookup(struct node *p,int value)
- { struct node *temp1,*temp2;
- if(p != NULL)
- { temp1 = p;
- while(temp1 != NULL)
- { temp2 = temp1;
- if(temp1->data > value) temp1 = temp1->left;
- else if(temp1->data < value) temp1 = temp1-
- >right; else return temp1; }
- return temp2;
- }
- else { printf("NO element in the tree\n"); exit(0); }
- }
82

Example Program C++


- struct node *search(struct node *p,int value) { struct node
- *x,*root; root = p; x = lookup(p,value);
- if(x->data == value) { printf("Inside search if\n"); splay(x,root); } else
- { printf("Inside search else\n"); splay(x,root); }
- }
- main()
- { struct node *root;//the root element
- struct node *x;//x is which element will come to root. int
- i; root = NULL; int choice = 0; int hand;
- while(1)
- { printf("\n\n 1.Insert"); printf("\n\n 2.Delete"); printf("\n\n 3.Search"); printf("\n\n
4.Display\n");
- printf("\n\n Enter your choice:");scanf("%d",&choice);
- if(choice==5) exit(0);
- switch(choice)
- { case 1: printf("\n\n Enter the element to be inserted:");
- scanf("%d", &ele); x = insert(root,ele);
- if(root != NULL) { splay(x,root);} root = x;
- break;
83

Example Program C++


- struct node *search(struct node *p,int value) { struct node
- *x,*root; root = p; x = lookup(p,value);
- if(x->data == value) { printf("Inside search if\n"); splay(x,root); } else
- { printf("Inside search else\n"); splay(x,root); }
- }
- main()
- { struct node *root;//the root element
- struct node *x;//x is which element will come to root. int
- i; root = NULL; int choice = 0; int hand;
- while(1)
- { printf("\n\n 1.Insert"); printf("\n\n 2.Delete"); printf("\n\n 3.Search"); printf("\n\n
4.Display\n");
- printf("\n\n Enter your choice:");scanf("%d",&choice);
- if(choice==5) exit(0);
- switch(choice)
- { case 1: printf("\n\n Enter the element to be inserted:");
- scanf("%d", &ele); x = insert(root,ele);
- if(root != NULL) { splay(x,root);} root = x;
- break;
84

Example Program C++


- case 2: if(root == NULL) { printf("\n Empty tree..."); continue; }
- printf("\n\n Enter the element to be delete:");
- scanf("%d", &ele); root = delete(root,ele); break;
- case 3: printf("Enter the element to be search\n");
- scanf("%d", &ele); x = lookup(root,ele); splay(x,root); case root = x; break;
- 4: printf("The elements are\n"); inorder(root); break;
- default: printf("Wrong choice\n"); break;
- } }}
- int data_print(struct node *x)
- { if ( x==NULL ) return 0;
- else return x->data; }
- /*some suggestion this code is not fully functional for example
- if you have inserted some elements then try to delete root then it may not work
- because we are calling right and left child of a null value(parent of root) which is not
- allowed and will give segmentation fault
- Also for inserting second element because of splaying twice(once in insert and one in main) will
- give error So I have made those changes but mainly in my cpp( c plus plus file) file, but I guess
- wiki will itself look into this and made these changes */

You might also like