creating red black tree

13
CREATING RED BLACK TREE CREATE A RED BLACK TREE WITH THE FOLLOWING ELEMENTS: 10,5,60,25,1,23

Upload: harman-kaur

Post on 15-Jul-2015

176 views

Category:

Engineering


2 download

TRANSCRIPT

Page 1: Creating red black tree

CREATING RED BLACK TREE

CREATE A RED BLACK TREE WITH THE FOLLOWING ELEMENTS:

10,5,60,25,1,23

Page 2: Creating red black tree

Red black tree properties.

• Each node is marked either red or black.

• Root node is always black

• Leaf nodes (null pointers) are always black.

• There should not be two consecutive reds.

• Number of black nodes is same from root to any leaf node.

Page 3: Creating red black tree

10,5,60,25,1,23

• INSERT 10

• INITIALLY TREE IS EMPTY. MAKE 10 AS ROOT AND MARK IT BLACK.

10

Page 4: Creating red black tree

10,5,60,25,1,23

• INSERT 5

• 5<10 SO, GO TO LEFT SUBTREE OF 10, WHICH IS EMPTY SO INSERT 5 TO LEFT OF 10 AND MARK IT RED.

10

5

Page 5: Creating red black tree

10,5,60,25,1,23

• INSERT 60

• 60>10 SO, GO TO RIGHT SUBTREE OF 10, WHICH IS EMPTY SO INSERT 60 TO RIGHT OF 10 AND MARK IT RED.

10

5 60

Page 6: Creating red black tree

10,5,60,25,1,23

• INSERT 25

• 25>10 SO, GO TO RIGHT SUBTREE OF 10

• 25<60 , GO TO LEFT SUBTREE OF 60, WHICH IS EMPTY SO INSERT 25 TO LEFT OF 60 AND MARK IT RED.

Page 7: Creating red black tree

It is of the form RL.

U = 25

P(u) = 60

G(u) = 10

S(p(u))=5 =>red

SINCE COLOR OF SIBLING OF P(U) is red. So recoloring will solve the problem.

5

10

60

25

RB TREE PROPERTY VIOLATED. NO CONSECUTIVE TWO REDS.

Page 8: Creating red black tree

• Make p(u) and s(p(u)) black.

• Make g(u) red.

• But in this example g(u) is root. So we donot make it red.

5

10

60

25

Page 9: Creating red black tree

10,5,60,25,1,23

• INSERT 1

• 1<10 SO, GO TO LEFT SUBTREE OF 10

• 1<5 , GO TO LEFT SUBTREE OF 5, WHICH IS EMPTY SO INSERT 1 TO LEFT OF 5 AND MARK IT RED.

5

10

60

251

Page 10: Creating red black tree

10,5,60,25,1,23• INSERT 23

• 23>10 SO, GO TO RIGHT SUBTREE OF 10

• 23<60 , GO TO LEFT SUBTREE OF 60,

• 23<25, GO TO LEFT SUBTREE OF 25,

WHICH IS EMPTY SO INSERT 23 TO LEFT

OF 25 AND MARK IT RED.

Page 11: Creating red black tree

RB TREE PROPERTY VIOLATED.(TWO CONSECUTIVE REDS (25 AND 23)

U=23

P(u)=25

G(u)=60

S(p(u))=nil (blank)

It is of the form LL.

U is left child of p(u) and p(u) is also left child of g(u).

• Since s(p(u)) is blank, Rotation is required.{make p(u) parent of u and g(u)

Make p(u) black and g(u) red.}

5

10

60

251

23

Page 12: Creating red black tree

Final RB tree with elements: 10,5,60,25,1,23

5

10

1 60

25

23

Page 13: Creating red black tree