Docsity

Data Structure - THREADED TREES - Notes, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Data Structure - THREADED TREES - Notes and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Threaded Trees

  • (^) Binary trees have a lot of

wasted space: the leaf nodes each have 2 null pointers

  • (^) We can use these pointers to

help us in inorder traversals and postorder traversals.

  • (^) We need to know if a pointer is

an actual link or a thread, so

we keep a boolean for each

pointer.

  • (^) Boolean- TRUE if child is

normal.

  • (^) Boolean -FALSE if a link is

replaced by a thread.

Structure of a node

  • (^) struct node {

node *left, *right; int data; bool leftThread, rightThread; }

1 5 0

Threaded Tree

Traversal

  • (^) We start at the leftmost node in the tree, print it, and follow its right thread.
  • (^) We output the node and continue to its right.
  • (^) If we follow a link to the right, we go to the leftmost node, print it, and continue.

Example of Threaded Tree

Only right links are shown for simplicity.

Threaded Tree

Traversal

Follow thread to right, print node

Output 1 3

Threaded Tree

Traversal

Follow link to right, go to leftmost node and print

Output 1 3 5

Threaded Tree

Traversal

Follow link to right, go to leftmost node and print

Output 1 3 5 6 7

Threaded Tree

Traversal

Follow thread to right, print node

Output 1 3 5 6 7 8

Threaded Tree

Traversal

Follow thread to right, print node

Output 1 3 5 6 7 8 9

11

Threaded Tree

Traversal

Follow link to right, go to leftmost node and print

Output 1 3 5 6 7 8 9

11 13

Insertion in a TBT

  • (^) T is to be inserted as right child of S.  (^) S has empty right tree.
    1. Right thread of S is made right thread of T.
  1. The left link of T is made a thread pointing to S.

T

S

T

S