Tree
Tree
31 mai 2021
Outline
Tree definitions
Tree declaration in C
Binary tree
Data
Leftmost Child Right-sibling
typedef struct
{
int data; // data of each node
struct treeNode * leftmost_child;
struct treeNode * right_sibling;
}treeNode;
treeNode * Root;
Tree example
A Data
Leftmost Child Right-sibling
B C D
E F G
A
H I J K
B C D
E F G
H I J K
Tree second example
1 Data
Leftmost Child Right-sibling
2 1
2
3 5
4 11 7
3 5
6 4
11 7
8
6
-2 9
-2 9
Binary trees
A binary tree is a tree such that
I every node has at most 2 children
I each node is labeled as being either a left child or a right child
Right child of a
Left child of a
Data
left right
pointer pointer
Full versus complete binary trees
Neither full nor complete Full and complete Neither full nor complete
Height of binary tree
typedef struct
{
DataType data; /*data of node; DataType: int, char, double..*/
struct node *left ; /* points to the left child */
struct node *right; /* points to the right child */
}node;
B A
E C
B C D
F G D
H E F G
J
H I J K
K
Binary tree traversal
A traversal is a systematic way to visit all nodes of a graph, a binary tree in the
present case
There are two very common traversals :
I Breadth First
I Depth First
Breadth First : In a breadth first traversal all of the nodes on a given level are
visited and then all of the nodes on the next level are visited. Usually in a left to
right fashion
On the tree below Breadth − first − search(2) visits the nodes in this order : 2, 4, 5,
7, 3, 10, 8, 1, 9, 11, 6
4 5
7 3 10 8
1 9
11
6
Depth first traversals
In a depth first traversal all the nodes of a subtree are visited prior to
visit another subtree
There are three common depth first traversals
I Inorder
I Preorder
I Postorder
Inorder tree traversal
Traverse the left subtree ; Visit the root ; Traverse the right subtree
InorderTreeWalk(x)
if x 6= NIL
InorderTreeWalk(x.left) ;
print(x.key) ;
InorderTreeWalk(x.right) ;
Call: InorderTreeWalk(A);
E D G F B H A L C M J
Call: PreorderTreeWalk(A);
A B D E F G H C L J M
Call: PostorderTreeWalk(A);
E G F D H B L M J C A