DSA - Trees
DSA - Trees
Full BT vs. Complete BT
A full binary tree of depth k is a binary tree of
depth k having 2 -1 nodes, k>=0.
A binary tree with n nodes and depth k is
complete iff its nodes correspond to the nodes numbered from 1 to n in the full
binary tree of depth k.
k
A
B
C
G
E
I
D
H
F
A
B
C
G E
K
D
J
F
I H
O N M L
Full binary tree of depth 4
Complete binary tree
Binary Tree Representations
If a complete binary tree with n nodes (depth =
log n + 1) is represented sequentially, then for
any node with index i, 1<=i<=n, we have:
parent(i) is at i/2 if i!=1. If i=1, i is at the root and
has no parent.
leftChild(i) is at 2i if 2i<=n. If 2i>n, then i has no
left child.
rightChild(i) is at 2i+1 if 2i +1 <=n. If 2i +1 >n,
then i has no right child.
Sequential
Representation
A
B
--
C
--
--
--
D
--
.
E
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
.
[16]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
A
B
C
D
E
F
G
H
I
A
B
E
C
D
A
B
C
G
E
I
D
H
F
(1) waste space
(2) insertion/deletion
problem
Linked Representation
typedef struct tnode *ptnode;
typedef struct tnode {
int data;
ptnode left, right;
};
data
left right
data
left right
Binary Tree Traversals
Let L, V, and R stand for moving left, visiting
the node, and moving right.
There are six possible combinations of traversal
lRr, lrR, Rlr, Rrl, rRl, rlR
Adopt convention that we traverse left before
right, only 3 traversals remain
lRr, lrR, Rlr
inorder, postorder, preorder
Arithmetic Expression Using BT
+
*
A
*
/
E
D
C
B
inorder traversal
A / B * C * D + E
infix expression
preorder traversal
+ * * / A B C D E
prefix expression
postorder traversal
A B / C * D * E +
postfix expression
level order traversal
+ * E * D / C A B
Inorder Traversal (recursive version)
void inorder(ptnode ptr)
/* inorder tree traversal */
{
if (ptr) {
inorder(ptr->left);
printf(%d, ptr->data);
indorder(ptr->right);
}
}
A / B * C * D + E
Preorder Traversal (recursive version)
void preorder(ptnode ptr)
/* preorder tree traversal */
{
if (ptr) {
printf(%d, ptr->data);
preorder(ptr->left);
predorder(ptr->right);
}
}
+ * * / A B C D E
Postorder Traversal (recursive version)
void postorder(ptnode ptr)
/* postorder tree traversal */
{
if (ptr) {
postorder(ptr->left);
postdorder(ptr->right);
printf(%d, ptr->data);
}
}
A B / C * D * E +
k-ary tree
In graph theory, a k-ary tree is a rooted tree in
which each node has no more than k children.
It is also sometimes known as a k-way tree, an
N-ary tree, or an M-ary tree.
A binary tree is the special case where k=2.
Thank You