t4. Threaded Binary Tree
t4. Threaded Binary Tree
1
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
◼ We have the pointers reference the next
node in an inorder traversal; called threads
◼ We need to know if a pointer is an actual link
or a thread, so we keep a boolean for each
pointer, right pointer points to its inorder
successor.
2
Threaded Tree Code
◼ Example code:
typedef struct Node {
Node *left, *right;
int rightThread;
}
3
Threaded Tree Example
6
3 8
1 5 7 11
9 13
4
Types of threaded binary trees
◼ Single Threaded: each node is threaded towards
either the in-order predecessor or successor (left
or right) means all right null pointers will point to
inorder successor OR all left null pointers will
point to inorder predecessor.
◼ Double threaded: each node is threaded
towards both the in-order predecessor and
successor (left and right) means all right null
pointers will point to inorder successor AND all
left null pointers will point to inorder
predecessor.
5
6
Threaded Tree Traversal
Output
6 1
3 8
1 5 7 11
9 13
Start at leftmost node, print it
7
Threaded Tree Traversal
Output
6 1
3
3 8
1 5 7 11
9 13
Follow thread to right, print node
8
Threaded Tree Traversal
Output
6 1
3
5
3 8
1 5 7 11
9 13
Follow link to right, go to
leftmost node and print
9
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
1 5 7 11
9 13
Follow thread to right, print node
10
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
7
1 5 7 11
9 13
Follow link to right, go to
leftmost node and print
11
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
7
1 5 7 11 8
9 13
Follow thread to right, print node
12
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
7
1 5 7 11 8
9
9 13
Follow link to right, go to
leftmost node and print
13
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
7
1 5 7 11 8
9
11
9 13
Follow thread to right, print node
14
Threaded Tree Traversal
Output
6 1
3
5
3 8 6
7
1 5 7 11 8
9
11
9 13 13
16
Two way Threading
17
Threaded Tree Modification
6
3 8
1 5 7 11
9 13
18