Docsity

Properties of Binary Tree, Threaded Binary Trees - Data Stuctures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Properties of Binary Tree, Threaded Binary Trees - Data Stuctures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

1

Properties of Binary Tree

Property: A binary tree with N internal nodes has

2N links: N-1 links to internal nodes and N+1 links

to external nodes.

2

Threaded Binary Tree

Property: A binary tree with N internal nodes has 2N links: N-1 links to internal nodes and N+1 links to external nodes.

D F

B C

G

A

E

E F

Internal links: 8 External links: 10

external link

internal link

4

Threaded Binary Trees

5

Threaded Binary Tree

 In many applications binary tree traversals are

carried out repeatedly.

 The overhead of stack operations during

recursive calls can be costly.

 The same would true if we use a non-recursive

but stack-driven traversal procedure

 It would be useful to modify the tree data

structure which represents the binary tree so as

to speed up, say, the inorder traversal process:

make it "stack-free".

7

Threaded Binary Tree

D F

B C

G

A

E

E F

Internal nodes: 9

External nodes: 10

external node

internal node

8

Threaded Binary Tree

 The threaded tree data structure will

replace these NULL pointers with pointers

to the inorder successor (predecessor) of

a node as appropriate.

 We'll need to know whenever formerly

NULL pointers have been replaced by non

NULL pointers to successor/predecessor

nodes, since otherwise there's no way to

distinguish those pointers from the

customary pointers to children.

10

Adding threads during insert

  1. t->L = p->L; // copy the thread t->LTH = thread; t->R = p; // *p is successor of *t t->RTH = thread;

p->L = t; // attach the new leaf p->LTH = child;

p

t

1

11

Adding threads during insert

  1. t->L = p->L; // copy the thread
  2. t->LTH = thread; t->R = p; // *p is successor of *t t->RTH = thread;

p->L = t; // attach the new leaf p->LTH = child;

p

t

1

2

13

Adding threads during insert

  1. t->L = p->L; // copy the thread
  2. t->LTH = thread;
  3. t->R = p; // *p is successor of *t
  4. t->RTH = thread;

p->L = t; // attach the new leaf p->LTH = child;

p

t

1

2 3

4

14

Adding threads during insert

  1. t->L = p->L; // copy the thread
  2. t->LTH = thread;
  3. t->R = p; // *p is successor of *t
  4. t->RTH = thread;
  5. p->L = t; // attach the new leaf p->LTH = child;

p

t

1

2 3

4

5

16

Threaded Binary Tree

17

Where is inorder successor?

Inorder successor of 4.

19

Where is inorder successor?

Inorder successor of 9.

Follow right thread to 14

20

Routine: nextInorder

TreeNode* nextInorder(TreeNode* p)

if(p->RTH == thread)

return(p->R);

else {

p = p->R;

while(p->LTH == child)

p = p->L;

return p;