creating red black tree

Post on 15-Jul-2015

177 Views

Category:

Engineering

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CREATING RED BLACK TREE

CREATE A RED BLACK TREE WITH THE FOLLOWING ELEMENTS:

10,5,60,25,1,23

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.

10,5,60,25,1,23

• INSERT 10

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

10

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

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

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.

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.

• 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

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

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.

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

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

5

10

1 60

25

23

top related