Data Structure & Algorithm: Prepared By: Patrick V. Mole, MIT
Data Structure & Algorithm: Prepared By: Patrick V. Mole, MIT
Data Structure & Algorithm: Prepared By: Patrick V. Mole, MIT
Structure &
Algorithm
Prepared by:
Patrick V. Mole, MIT
5
Binary Tree
Binary Tree Data Structure
B C
Left subtree
Right subtree
D F G
Edges Leaves
H I
K M
Example:
Node A is the root. Nodes B and C are A’s children. Nodes B and D together form
a subtree. Node B has two children: Its left child is the empty tree and its right
child is D. Nodes A, C, and E are ancestors of G. Nodes D, E, and F make up level
2 of the tree; node A is at level 0. The edges from A to C to E to G form a path of
length 3. Nodes D, G, H, and I are leaves. Nodes A, B, C, E, and F are internal
nodes. The depth of I is 3. The height of this tree is 3.
Example Tree Calculations
Recall: Height of a tree is the maximum number of A
edges from the root to a leaf. Height = 4
A
A D F G
Height = 0 B Height = 1
H I
What is the depth of node G?
Depth = 2
K M
Difference between Full &
Complete Binary Tree
In this traversal method, the left subtree is visited first, then the
root and later the right sub-tree.
Algorithm
Step 1 − Recursively traverse
left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse
right subtree.
OUTPUT: D → B → E → A → F → C → G
Pre-order Traversal (root, left subtree, right subtree )
In this traversal method, the root node is visited first, then the left
subtree and finally the right subtree.
Algorithm
Step 1 − Visit root node.
Step 2 − Recursively traverse
left subtree.
Step 3 − Recursively traverse
right subtree.
OUTPUT: A → B → D → E → C → F → G
Post-order Traversal (left subtree, right subtree, root)
In this traversal method, we first traverse the left subtree, then the
right subtree and finally the root node.
Algorithm
Step 1 − Recursively traverse
left subtree.
Step 2 − Recursively traverse
right subtree.
Step 3 − Visit root node.
OUTPUT: D → E → B → F → G → C → A