Lecture 08 TreeI 20230309
Lecture 08 TreeI 20230309
Data Structures
Lecture 8
1
Tree I
2
Nature Lover’s View Of A Tree
leaves
branches
root 3
Computer Scientist’s View
root
leaves
branches
nodes 4
Java’s Classes
Object root
children of root
RuntimeException
5
leaf great grand child of root
Definition
6
Subtrees
Object root
RuntimeException
7
Leaves
Object
RuntimeException
8
Parent, Grandparent, Siblings, Ancestors, Descendants
RuntimeException
9
Levels
Object Level 1
Level 2
Number Throwable OutputStream
RuntimeException
10
Level 4
Caution
RuntimeException
Level 4 12
Node Degree = Number Of Children
Object 3
0 0 1 0
Integer Double Exception FileOutputStream
RuntimeException 0
13
Tree Degree = Max Node Degree
Object 3
0 0 1 0
Integer Double Exception FileOutputStream
RuntimeException 0
Degree of tree = 3.
14
Tree - Exercise
• Find the followings:
1.Root
2.Leave
3.Siblings
4.Height
5.Depth
6.Tree Degree
15
Binary Tree
• Finite (possibly empty) collection of elements.
• A nonempty binary tree has a root element.
• The remaining elements (if any) are partitioned into
two binary trees.
• These are called the left and right subtrees of the
binary tree.
Root
Left Right
16
Differences Between a Tree &
a Binary Tree
• Binary tree:
– No node may have a degree more than 2.
• Tree:
– No limit on the degree of a node in a tree.
17
Differences Between a Tree &
a Binary Tree
• The subtrees of a binary tree are ordered;
those of a tree are not ordered.
a a
19
Structure for a Tree
A Node is represented by an object with
data variables:
• Element
• A parent node
• A sequence of children nodes
(parent node)
20
Structure for a Tree
A F A D F
D
C E
21
C E
Structure for a Tree
- Create the root
B
class Tree:
def __init__(self, data): A F
self.children = [] D
self.data = data
C E
root = Tree("B")
Tree.py
22
Structure for a Tree B
- Add a child A
D
F
C E
class Tree:
def __init__(self, data):
self.children = []
self.data = data
left = Tree("A")
middle = Tree("D")
right = Tree("F") A
root = Tree("B")
root.children = [left, middle, right]
Tree.py
23
B
Structure for a Tree
A F
- Add a grandchild D
class Tree: C E
def __init__(self, data):
self.children = []
self.data = data
left = Tree("A") A D F
middle = Tree("D")
right = Tree("F")
root = Tree("B")
root.children = [left, middle, right]
grandchildC = Tree("C")
grandchildE = Tree("E")
middle.children = [grandchildC, grandchildE]
24
C E
Binary Tree ADT and
Implementation in Linked Nodes
25
Binary Tree
• A binary tree is a tree
with the following
A
properties:
1. Each internal node has
B C
one or two children left child right child
2. The children of a node
D E F G
are an ordered pair left child
left child right child
(left and right)
H I
3. We call the children of
right child
an internal node left
child and right child
26
Binary Tree
Alternative recursive definition:
a binary tree is either
• a tree consisting of a single A
node, or
• a tree whose root has an B C
27
BinaryTree Node
A
class BinaryTreeNode:
def __init__(self, data):
self.left = None
self.right = None B C
self.data = data left child right child
a = BinaryTreeNode("A")
F G
left child right child
BinaryTree.py
28
BinaryTree Node
# Create Binary Tree A
a = BinaryTreeNode("A")
b = BinaryTreeNode("B")
c = BinaryTreeNode("C") left right
B C
a.setLeftChild(b)
a.setRightChild(c)
f = BinaryTreeNode("F") F G
g = BinaryTreeNode("G") left right
c.setLeftChild(f)
c.setRightChild(g)
30
Properties
- Full Binary Tree
• A full binary tree of a given height h has
2h – 1 nodes.
1 2
3 4 5 6
7 8 9 10 11 12 13 14 32
Complete Binary Tree
• all levels are completely filled except
possibly the last level and the last level
has all keys as left as possible.
0
1 2
3 4 5 6
7 8 9
• Example, Complete binary tree with 10 nodes.
• The size n of a complete binary tree of height
h satisfies 2h-1 <= n <= 2h – 1 33
Proper Binary Trees
34
Proper Binary Trees
Given the following definitions: Properties:
35
Examples of Usage of Binary
Trees
36
Arithmetic Expression Tree
- Binary tree associated with an arithmetic expression
internal nodes: operators
external nodes: operands
+
Example: arithmetic expression
tree for the expression:
(2 (a - 1) + (3 b)) 2 - 3 b
a 1
37
Decision Tree
39
Binary Tree Traversal
• Many binary tree operations are done by
performing a traversal of the binary tree.
• In a traversal, each element of the binary tree
is visited exactly once.
• During the visit of an element, all action
(make a clone, display, evaluate the operator,
etc.) with respect to this element is taken.
40
Binary Tree Traversal Methods
• Preorder (get prefix expression)
• Inorder (get infix expression)
• Postorder (get postfix expression)
• Level order
41
Preorder Traversals of a Binary
Tree
42
Preorder Traversal
• A traversal visits the nodes of
a tree in a systematic manner Algorithm preOrder(T,v)
• In a preorder traversal, a visit(v)
node is visited before its for each child w of v
descendants
• Application: print a structured preOrder (T,w)
document
1
Make Money Fast!
2 5
1. Motivations 2. Methods
6 7
3 4
2.1 Stock 2.2 Ponzi
1.1 Greed 1.2 Avidity Fraud Scheme
43
Preorder Example (visit = print)
a
b c
abc
44
Preorder Example (visit = print)
a
b c
f
d e
g h i j
abdghei cf j
45
Preorder Of Expression Tree
/
* +
e f
+ -
a b c d
/ * +a b - c d +e f
demo: BinaryTree2.py
47
Inorder
Traversals of a Binary Tree
48
Inorder Traversal
Algorithm inOrder(v)
• In an inorder if leftChild(v) null
traversal a node is inOrder(leftChild(v))
visited after its left visit(v)
subtree and before if rightChild(v) null
its right subtree inOrder(rightChild(v))
4 /
2 6
+ -
5 7
1 3
6 8 10 2
49
Inorder Example (visit = print)
a
b c
bac
50
Inorder Example (visit = print)
a
b c
f
d e
g h i j
gdhbei af j c
51
Inorder By Projection
a
b c
f
d e
g j
h i
g d h b e i a f j c
52
Inorder Of Expression Tree
/
* +
e f
+ -
a b c d
a + b * c - d/ e + f
demo: BinaryTree2.py
54
Postorder Traversals of a Binary
Tree
55
Postorder Traversal
• In a postorder traversal, a
node is visited after its Algorithm postOrder(T,v)
descendants for each child w of v
• Application: compute space postOrder (T,w)
used by files in a directory visit(v)
and its subdirectories
7
cs16/
3 6
homeworks/ programs/
1 2 4 5
h1c.doc h1nc.doc DDR.java Stocks.java
3K 2K 10K 25K
56
Postorder Traversal
demo: BinaryTree2.py
57
Postorder Example (visit = print)
a
b c
bca
58
Postorder Example (visit = print)
a
b c
f
d e
g h i j
ghdi ebj f ca
59
Postorder Of Expression Tree
/
* +
+ - e f
a b c d
a b +c d - * e f + /
61
Level Order
demo: BinaryTree2
62
visit
Level Order 0
1 2
levelorder(root)
q = empty queue
q.enqueue(root)
1 2
while not q.empty do
queue
t := q.dequeue() Level 2 nodes are
visit(t) placed in the queue
before Level 3 nodes
if t.left ≠ null
q.enqueue(t.left)
if t.right ≠ null
q.enqueue(t.right) 63
Level-Order Example (visit = print)
a
b c
f
d e
g h i j
abcdef ghi j
64
Arithmetic Expression Using Binary
Tree inorder traversal
A/B*C*D+E
+
infix expression
* E preorder traversal
+**/AB CDE
prefix expression
* D
postorder traversal
/ C AB/C*D*E+
postfix expression
A B
level order traversal
+ * E * D / C A65B
Exercise
• As an example consider the following tree and
its four traversals:
• PreOrder – 8, 5, 9, 7, 1, 12, 2, 4, 11, 3
• InOrder – 9, 5, 1, 7, 2, 12, 8, 4, 3, 11
• PostOrder – 9, 1, 2, 12, 7, 5, 3, 11, 4, 8
• LevelOrder – 8, 5, 4, 9, 7, 11, 1, 12, 3, 2
66
Construct the tree
• Preorder: JCBADEFIGH
• In-order: ABCEDFJGIH
67
Summary
• General Trees
– Creation of Trees
• Binary trees
– Binary Tree Implementation
– Full, Complete and Proper
– Applications: e.g. Decision Trees
• Tree Traversal
– Preorder,
– Postorder,
– Inorder or
– Level order
68