Professional Documents
Culture Documents
Representation
ROOT OF
TREE T
T1
T2
T3
T4
T5
SUBTREES
Prof. Gayathri. P, SCSE, VIT University
Binary Trees
A binary tree is a tree in which no node can
have more than two subtrees i.e atmost 2
children.
In other words, a node can have zero, one, or
two subtrees.
These subtrees are designated as the left
subtree and the right subtree.
T1
T2
SUBTREES
Prof. Gayathri. P, SCSE, VIT University
Array Representation
Root is stored at index 1 of the array.
Left child at 2i and right child at 2i+1 where I is the index of the
parent.
If array index begins with 0, then root at 0, left child at 2i+1 and right
child at 2i+2 where i is the index of the parent.
a1
b
4
c
5
8
h
tree[]
7
g
10
j
a b c d e f g h i j
0
5
10
Prof. Gayathri. P, SCSE, VIT University
10
Linked List
Struct BinaryTreeNode
{
int element;
struct BinaryTreeNode *leftChild; // pointer to left
subtree
11
a
b
c
e
# - Null
leftChild
element
rightChild
Prof. Gayathri. P, SCSE, VIT University
g
#
#
12
BT Traversal
Refer PDF file
Also Refer C program document
Fourth type of traversal is Level order
Visit the nodes from top level to bottom level. In each level,
visit nodes from left to right.
Level order traversal for the example tree is
7 1 9 0 3 8 10 2 5 4 6
13
Terminology - Definition
Number of nodes = 9
The degree of a node is the number of sub trees of the node
The degree of A is 3; the degree of C is 0; the degree of B is 2 .
The node with degree 0 or node without any children is a leaf or terminal
node.
The node with children is a non-terminal node. B, F, A
A node that is not a root or a leaf is known as an internal node.
All non-terminal nodes are parents and they have subtrees.
The roots of these subtrees are the children of the parent node.
Children of the same parent are siblings.
14
Path Length - The length of path is the number of edges on the path
There is a path of length zero from every node to itself.
In a tree there is one and only one path from the root to each node.
Depth of a node - The depth of a node is the length of the path from
the root to the node. The root is at depth 0.
Depth of the tree - The depth of a tree is the depth of its deepest leaf.
Height of a node - The height of any node is the longest path from the
node to any leaf. The height of any leaf is 0.
Height of the tree - The height of a tree is the height of its root.
15
data
link 1
link 2
...
link n
How many link fields are
needed in such a representation?
16
A Tree Node
Every tree node:
object useful information
children pointers to its children nodes
O
O
Prof. Gayathri. P, SCSE, VIT University
17
C
F
D
H
data
right sibling
left child
18
Tree Implementation
struct tnode {
int key;
struct tnode* lchild;
struct tnode* sibling;
} *ptnode;
19
B
C
D
A
F
B
E
G
J
I
General Trees
J
20
21