BLM19202E / BLM22212E /
SEN22212E
Data Structures
Trees (AÄaçlar)
Outline
• Definitions
• Implementation of Trees
• Binary Trees
• Tree Traversals & Expression Trees
• Binary Search Trees
18.03.2024
Data Structures
2
Trees
18.03.2024
Data Structures
3
Linear List vs Tree
• Linear lists are useful for serially ordered data.
• (e0, e1, e2, …, en-1)
• Days of week.
• Months in a year.
• Students in this class.
• Trees are useful for hierarchically ordered data.
• Employees of a corporation.
• President, vice presidents, managers, and so on.
• Java’s classes.
• Object is at the top of the hierarchy.
• Subclasses of Object are next, and so on.
18.03.2024
Data Structures
4
Java’s Classes
Object
root
children of root
Number
Integer
Double
Throwable
OutputStream
Exception
FileOutputStream
grand children of root
RuntimeException
great grand child of root
Linux/Unix File System
18.03.2024
Data Structures
6
Definition
• A tree is a collection of nodes (vertices) where the collection may be
empty.
• Otherwise, the collection consists of a distinguished node r, called
the root, and zero or more non-empty (sub)trees T1, …, Tk, each of
whose roots are connected by a directed edge to r.
18.03.2024
Data Structures
7
More Definitions
• In-degree of a vertex is the number of edges arriving at that vertex.
• Out-degree of a vertex is the number of edges leaving that vertex.
• Nodes with out-degree=0 (no children) are called the leaves of the
tree.
• Root is the only node in the tree with in-degree=0.
18.03.2024
Data Structures
8
More Definitions
• The child C of a node A is the node that is connected to A by a single
edge. Then, A is the parent of C.
• Grandparent and grandchild relations can be defined in the same
manner.
• Nodes with the same parent are called siblings.
18.03.2024
Data Structures
9
A General Tree Example
• Root
•A
• Children of A
• B, C, D, E, F.
• Leaves of the tree
• C, D, G, H, I, K, L, M,
and N.
• Siblings of G
• H and I.
18.03.2024
Data Structures
10
More Definitions
• A path from a node n1 to nk is defined as a sequence of nodes n1,…, nk such that ni
is the parent of ni+1 for 1ïĢi<k.
• The length of this path is the number of edges on the path, i.e., k-1.
• There is exactly one path from the root to each node.
http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/
18.03.2024
Data Structures
11
More Definitions
• The depth of any node ni is the length of the unique path from the root to ni.
• The depth of root is 0.
• D's depth is 2.
http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/
18.03.2024
Data Structures
12
More Definitions
• The level of a node is defined by 1 + the number of connections between the node
and the root.
http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/
18.03.2024
Data Structures
13
More Definitions
• The height of any node ni is the length of the longest path from ni to a
leaf.
• The height of a tree is the height of its root.
18.03.2024
Data Structures
14
Remarks
• The height of all leaves are 0.
• The height of C is 0.
• The height of the tree is 3.
• If there is a path from n1 to n2, then n1 is an ancestor of n2 and n2 is a
descendant of n1 .
18.03.2024
Data Structures
15
More Definitions
A subtree of a tree T is a tree consisting of a node in T and all of its descendants
in T
18.03.2024
Data Structures
16
Implementation of Trees
• One way to implement a tree would be to have a pointer in each node to
each child, besides the data it holds. This is infeasible!
• Q:Why?
• A:The number of children of each node is variable, and hence, unknown.
• Another option would be to keep the children in a linked list where the first
node of the list is pointed to by the pointer in the parent node as a header.
• A typical tree node declaration in Java would be as follows:
public class Node {
int data;
Node childptr, siblingptr;
}
18.03.2024
Data Structures
17
Implementation of Trees
18.03.2024
Data Structures
18
Binary Trees (BTs)
• A binary tree is a tree of nodes with at most two children.
• Declaration of a typical node in a binary tree
class BTNodeType {
int data;
BTNodeType left;
BTNodeType right;
}
• Average depth in BTs: ð( ð)
18.03.2024
Data Structures
19
A Binary Tree Topology
18.03.2024
Data Structures
20
Minimum Number Of Nodes
What is the minimum number of nodes in a binary tree whose
height is h?
minimum number of nodes is (h+1)
18.03.2024
Data Structures
21
Maximum Number Of Nodes
What is the maximum number of nodes in a binary tree whose
height is h?
maximum number of nodes will be when all levels are completely
full
maximum number of nodes is
1 + 2 + 4 + 8 + âŊ + 2â = 2â+1 − 1
18.03.2024
Data Structures
22
Number Of Nodes & Height
• Let n be the number of nodes in a binary tree whose height is h.
• If there are n nodes in a binary search tree, maximum height of the
binary search tree is ð − 1 and minimum height is log 2 ð .
âðððâðĄ = log 2 5 = 2
âðððâðĄ = 5 − 1 = 4
18.03.2024
Data Structures
23
Full Binary Tree
• A full binary tree of a given height h has 2h+1 – 1 nodes
18.03.2024
Data Structures
24
Complete Binary Tree
• A complete binary tree is a binary tree in which every level, except
possibly the last, is completely filled, and all nodes are as far left as
possible
18.03.2024
Data Structures
25
Tree Traversals
• A tree can be traversed recursively in three different ways:
• in-order traversal (left-node-right or LNR)
• First recursively visit the left subtree.
• Next process the data in the current node.
• Finally, recursively visit the right subtree.
• pre-order traversal (node-left-right or NLR)
• post-order traversal (left-right-node or LRN)
• Traversal requires O(n) time, since it must visit every node
18.03.2024
Data Structures
26
In-order traversal
In-order (Left, Root, Right) : 4 2 5 1 3
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
18.03.2024
Data Structures
27
In-order traversal
void printInorder(Node node) {
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.key + " ");
42513
/* now recur on right child */
printInorder(node.right);
}
18.03.2024
Data Structures
28
Pre-order traversal
Pre-order (Root, Left, Right) : 1 2 4 5 3
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
18.03.2024
Data Structures
29
Pre-order traversal
void printPreorder(Node node) {
if (node == null)
return;
/* first print data of node */
System.out.print(node.key + " ");
/* then recur on left sutree */
printPreorder(node.left);
12453
/* now recur on right subtree */
printPreorder(node.right);
}
18.03.2024
Data Structures
30
Post-order traversal
Post-order (Left, Right, Root) : 4 5 2 3 1
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
18.03.2024
Data Structures
31
Post-order traversal
void printPostorder(Node node) {
if (node == null)
return;
// first recur on left subtree
printPostorder(node.left);
// then recur on right subtree
printPostorder(node.right);
45231
// now deal with the node
System.out.print(node.key + " ");
}
18.03.2024
Data Structures
32
Example
In-order (LNR)
Pre-order (NLR)
Post-Order (LRN)
In-order (LNR)
Pre-order (NLR)
Post-Order (LRN)
18.03.2024
: 4 10 12 15 18 22 24 25 31 35 44 50 66 70 90
: 25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
: 4 12 10 18 24 22 15 31 44 35 66 90 70 50 25
Data Structures
33
Example
• Inorder traversal of the tree (LNR): 4 8 2 5 1 6 3 7
• Postorder traversal of the tree (LRN): 8 4 5 2 6 7 3 1
• Draw the tree.
18.03.2024
Data Structures
34
Expression Trees
• Prefix, postfix and infix formats of arithmetic expressions
18.03.2024
Infix
Postfix
Prefix
A+B
AB+
+AB
A/(B+C)
ABC+/
/A+BC
A/B+C
AB/C+
+/ABC
A-B*C+D/(E+F)
ABC*-DEF+/+
+-A*BC/D+EF
A*((B+C)/(D-E)+F)-G/(H-I)
ABC+DE-/F+*GHI-/-
-*A+/+BC-DEF/G-HI
Data Structures
35
Construction of an Expression Tree
from Postfix Expressions
• Initialize an empty stack of subtrees
• Repeat
• Get token;
• if token is an operand
• Push it as a subtree
• else
• pop the last two subtrees and form & push a subtree such that root is the current
operator and left and right operands are the former and latter subtrees, respectively
• Until the end of arithmetic expression
http://mimoza.marmara.edu.tr/~berna.altinel/courses/cse225/
18.03.2024
Data Structures
36
Example to Construction of Expression Trees
Empty Stack of subtrees
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
37
Example to Construction of Expression Trees - 1
Stack of subtrees
A
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
38
Example to Construction of Expression Trees - 2
Stack of subtrees
A B
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
39
Example to Construction of Expression Trees - 3
Stack of subtrees
A B C
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
40
Example to Construction of Expression Trees - 4
Stack of subtrees
A +
B C
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
41
Example to Construction of Expression Trees - 5
Stack of subtrees
A + D
B C
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
42
Example to Construction of Expression Trees - 6
Stack of subtrees
A + D E
B C
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
43
Example to Construction of Expression Trees - 7
Stack of subtrees
A
+
-
B CD E
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
44
Example to Construction of Expression Trees - 8
Stack of subtrees
/
A
+
-
B CD E
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
45
Example to Construction of Expression Trees - 9
Stack of subtrees
/
A
F
+
-
B CD E
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
46
Example to Construction of Expression Trees - 10
Stack of subtrees
+
A /
+
F
-
B CD E
ABC+DE-/F+*GHI-/18.03.2024
Data Structures
47
Example to Construction of Expression Trees - 11
Stack of subtrees
*
A
+
/
+
F
-
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
48
Example to Construction of Expression Trees - 12
Stack of subtrees
*
G
A
+
/
+
F
-
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
49
Example to Construction of Expression Trees - 13
Stack of subtrees
*
G
A
H
+
/
+
F
-
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
50
Example to Construction of Expression Trees - 14
Stack of subtrees
*
G
A
H
I
+
/
+
F
-
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
51
Example to Construction of Expression Trees - 15
Stack of subtrees
*
G
A
-
+
/
+
F
H
I
-
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
52
Example to Construction of Expression Trees - 16
Stack of subtrees
*
/
A
+
/
+
G
-
F
-
H
I
ABC+DE-/F+*GHI-/B CD E
18.03.2024
Data Structures
53
Example to Construction of Expression Trees - 17
Stack of subtrees
*
/
A
+
/
+
G
-
F
-
H
I
ABC+DE-/F+*GHI-/18.03.2024
B CD E
Data Structures
54
Example
Given the postfix expressions: 3 7 1 + 4 / * 17 5 - +
Construct the expression tree
18.03.2024
Data Structures
55
3 7 1 + 4 / * 17 5 - +
18.03.2024
Data Structures
56
Binary Search Trees (BSTs)
BSTs are binary trees with keys placed in each node in such a manner that
the key of a node is
greater than all keys in its left sub-tree
and
less than all keys in its right sub-tree.
Here, we assume no replication of keys. For replicating keys, the relations are
modified as “greater than or equal to” or “less than or equal to” depending on the
application.
https://www.cs.usfca.edu/~galles/visualization/BST.html
18.03.2024
Data Structures
57
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
18.03.2024
Data Structures
58
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
18.03.2024
Data Structures
59
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
24
18.03.2024
Data Structures
60
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
24
20
18.03.2024
Data Structures
61
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
24
20
18.03.2024
32
Data Structures
62
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
8
24
20
18.03.2024
32
Data Structures
63
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
8
24
12
18.03.2024
20
32
Data Structures
64
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
18.03.2024
20
32
Data Structures
65
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
18.03.2024
20
72
32
Data Structures
66
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
18
18.03.2024
Data Structures
67
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
96
18
18.03.2024
Data Structures
68
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
96
18
18.03.2024
Data Structures
69
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
96
18
17
18.03.2024
Data Structures
70
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
18
96
60
17
18.03.2024
Data Structures
71
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
18
60
96
98
17
18.03.2024
Data Structures
72
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
18
60
96
68
98
17
18.03.2024
Data Structures
73
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
72
32
64
18
60
96
68
84
98
17
18.03.2024
Data Structures
74
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
20
18
72
32
64
36
60
96
68
84
98
17
18.03.2024
Data Structures
75
A Binary Search Tree Example
48 16 24 20 32 8 12 54 72 18 96 64 17 60 98 68 84 36 30
48
16
54
8
24
12
72
20
18
32
30
64
36
60
96
68
84
98
17
18.03.2024
Data Structures
76
Recursive Search Function in BSTs
18.03.2024
Data Structures
77
Recursive Search Function in BSTs
public Node search(Node root, int key)
{
// Base Cases: root is null or key is present at root
if (root == null || root.key==key)
return root;
// val is greater than root's key
if (root.key > key)
return search(root.left, key);
// val is less than root's key
return search(root.right, key);
}
18.03.2024
Data Structures
78
Analysis
• In the worst case this algorithm must search from the root of the tree
to the leaf farthest from the root, the search operation takes time
proportional to the tree's height.
• On average, binary search trees with n nodes have O(logn) height
• However, in the worst case, binary search trees can have O(n) height
18.03.2024
Data Structures
79
Non-recursive FindMin Function in BSTs
int findMin(Node node) {
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null) {
current = current.left;
}
return (current.data);
}
find-min takes O(h) time where h is the height of the tree
18.03.2024
Data Structures
80
Recursive FindMax Function in BSTs
Node findMax(Node node) {
if(node == null) return null;
if(node.right == NULL) return node;
return findMax(node.right);
}
find-max takes O(h) time where h is the height of the tree
18.03.2024
Data Structures
81
Insert
18.03.2024
Data Structures
82
Recursive Insert Function in BSTs
void insert(int key) {
root = insertRec(root, key);
/* A recursive function to insert a new key in BST */
Node insertRec(Node root, int key) {
}
/* If the tree is empty, return a new node */
if (root == null) {
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
18.03.2024
Data Structures
83
Analysis
This operation requires time proportional to the height of the tree in
the worst case, which is O(log n) time in the average case over all trees,
but O(n) time in the worst case.
18.03.2024
Data Structures
84
Remove a node from a BST
• Three cases:
Element is in a leaf.
Element is in a degree 1 node.
Element is in a degree 2 node.
18.03.2024
Data Structures
85
Remove From A Leaf
20
10
6
2
40
15
8
7
Remove a leaf element. key = 7
30
18
25
35
Remove From A Leaf (contd.)
20
10
6
2
40
15
8
7
Remove a leaf element. key = 35
30
18
25
35
Remove From A Degree 1 Node
20
10
6
2
40
15
8
30
18
7
Remove from a degree 1 node. key = 40
25
35
Remove From A Degree 1 Node (contd.)
20
10
6
2
40
15
8
30
18
7
Remove from a degree 1 node. key = 15
25
35
Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
7
Remove from a degree 2 node. key = 10
25
35
Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
25
35
7
Replace with largest key in left subtree (or smallest in right subtree).
Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
25
35
7
Replace with largest key in left subtree (or smallest in right subtree).
Remove From A Degree 2 Node
20
8
6
2
40
15
8
30
18
25
35
7
Replace with largest key in left subtree (or smallest in right subtree).
Remove From A Degree 2 Node
20
8
6
2
40
15
8
30
18
7
Largest key must be in a leaf or degree 1 node.
25
35
Another Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
7
Remove from a degree 2 node. key = 20
25
35
Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
7
Replace with largest in left subtree.
25
35
Remove From A Degree 2 Node
20
10
6
2
40
15
8
30
18
7
Replace with largest in left subtree.
25
35
Remove From A Degree 2 Node
18
10
6
2
40
15
8
30
18
7
Replace with largest in left subtree.
25
35
Recursive Remove Function in BSTs
// This method mainly calls deleteRec()
void deleteKey(int key)
{
root = deleteRec(root, key);
}
/* A recursive function to insert a new key in BST */
Node deleteRec(Node root, int key)
{
/* Base Case: If the tree is empty */
if (root == null) return root;
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);
// if key is same as root's key, then This is the node to be deleted
else
{ // node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node with two children: Get the inorder successor (smallest
// in the right subtree)
root.key = minValue(root.right);
// Delete the inorder successor
root.right = deleteRec(root.right, root.key);
}
return root;
}
18.03.2024
Data Structures
99
Analysis
• Although this operation does not always traverse the tree down to a
leaf, this is always a possibility; thus in the worst case it requires time
proportional to the height of the tree
18.03.2024
Data Structures
100
Time Complexity in Big-O notation
Average
Worst Case
Space
O(n)
O(n)
Search
O(logn)
O(n)
Insert
O(logn)
O(n)
Remove
O(logn)
O(n)
Algorithm
18.03.2024
Data Structures
101
Binary Search Trees Visualization
• https://www.cs.usfca.edu/~galles/visualization/BST.html
18.03.2024
Data Structures
102
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )