Binary-Trees
Binary-Trees
Computing Laboratory
http://www.isical.ac.in/~dfslab
(Recursive) Definition
A binary tree over a domain D is either:
the empty set (called an empty binary tree); or
a 3-tuple ⟨S1 , S2 , S3 ⟩ where
S1 ∈ D, (called the root) and
S2 and S3 are binary trees over D (called the left and right subtree
resp.)
Height: h
Number of nodes: n
Number of leaves: l
Preorder
Inorder
Postorder
Conventional implementation:
typedef struct tnode {
DATA d;
struct tnode *left, *right;
struct tnode *parent; // optional
} TNODE;
Alternative implementation:
typedef struct tnode {
DATA d;
int left, right;
int parent; //optional
} TNODE;
Initially:
Alternative implementation: root = -1
typedef struct tnode { DATA left right
DATA d; free −→ 0 — 1 -1
int left, right; 1 — 2 -1
int parent; //optional
2 — 3 -1
} TNODE;
3 — 4 -1
. .
. .
. .
One initial malloc and reallocs as needed
n-1 — -1 -1
All nodes located within the same array
Alternative implementation:
root = 0
DATA left right A
0 A 1 2
1 B 3 4
2 C -1 5 B C
3 D -1 -1
4 E -1 -1
5 F -1 -1
D E F
free −→ 6 — 7 -1
.. ..
. .
n-1 — -1 -1
Computing Lab (ISI) Binary Trees 7 / 10
Problems – I