Algorithms Lecture11 Trees 08052024 010112pm
Algorithms Lecture11 Trees 08052024 010112pm
Family Tree
Q uresh
G halib M uh arib
T aiem Luayy
A uf Ka'ab A m ir H irs
H u sa is S ehm M urrah Ja m ha A di
Z ah ra Q usayy
M uham m ad
(PBUH)
Tree - Definition
A tree is a finite set of one or more nodes such that:
1. There is a specially designated node called the
root.
2. The remaining nodes are partitioned in n 0
disjoint sets T1, T2, …, Tn, where each of these
sets is a tree.
3. T1, T2, …, Tn are called the sub-trees of the root.
Recursive Definition
Sub-trees
Family Tree
Q uresh root
G halib M uh arib
T aiem Luayy
A uf Ka'ab A m ir H irs
H u sa is S ehm M urrah Ja m ha A di
Banu Hashim
T aiem Q ulaab M akh zo om
Z ah ra Q usayy
M uham m ad
(PBUH)
Tree
B F K
C H D L X
Q G M I N P
Node Types
A
B F K
C H D L X
Q G M I N P
B F K
C H D L X
Q G M I N P
Degree 1 Degree 3
Degree 0 Degree 2
Level of a Node
Distance from the root
A
B F K
C H D L X
Q G M I N P
Level 0 Level 2
Level 1 Level 3
A A
B K B
C H L X C
Q M P Q
M
Properties of Binary Trees
• The maximum number of nodes on level i
of a binary tree is 2i
• The maximum number of nodes in a binary
tree of height k is 2k – 1
Full Binary Tree
A binary tree of height k having 2k – 1 nodes is called a full binary tree
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Complete Binary Tree
A binary tree that is completely filled, with the possible exception of the
bottom level, which is filled from left to right, is called a complete
binary tree
2 3
4 5 6 7
8 9 10 11 12
Binary Tree
No node has a degree > 2
struct TreeNode {
int data;
TreeNode *left, *right; // left subtree and right subtree
};
Class BinaryTree {
private:
TreeNode * root;
public:
BinaryTree() { root = NULL; }
void add (int data);
void remove (int data);
void InOrder(); // In order traversal
~ BinaryTree();
};
Binary Tree Traversal
In order Traversal (LNR)
void BinaryTree::InOrder() // work horse function
{
InOrder(root);
}
B K
C H L X if (t) {
InOrder(t->left);
Q M P
visit(t);
InOrder(t->right);
Q C M B H A L K X P }
Binary Tree Traversal
Pre Order Traversal (NLR)
void BinaryTree::PreOrder()
{
PreOrder(root);
}
B K
C H L X if (t) {
visit(t);
Q M P
PreOrder(t->left);
PreOrder(t->right);
A B C Q M H K L X P }
Binary Tree Traversal
Post Order Traversal (LRN)
void BinaryTree::PostOrder() // work horse function
{
PostOrder(root);
}
B K
C H L X if (t) {
PostOrder(t->left);
Q M P
PostOrder(t->right);
visit(t);
Q M C H B L P X K A }
Binary Tree Traversal
A
B K
C H L X
Q M P
+ /
A * D *
B C E F
LNR: A+B*C-D/E*F
NLR: -+A*BC/D*EF
LRN: ABC*+DEF*/-
BinaryTree ::~ BinaryTree();
Which Algorithm?
LRN