0% found this document useful (0 votes)
11 views68 pages

Lecture 08 TreeI 20230309

The document discusses trees and binary trees. It defines trees as a set of nodes where one node is the root and other nodes are partitioned into subtrees. It defines binary trees as trees where each node has at most two children, called left and right children.

Uploaded by

KaHim Chan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views68 pages

Lecture 08 TreeI 20230309

The document discusses trees and binary trees. It defines trees as a set of nodes where one node is the root and other nodes are partitioned into subtrees. It defines binary trees as trees where each node has at most two children, called left and right children.

Uploaded by

KaHim Chan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

SEHH2239

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

Number Throwable OutputStream

Integer Double Exception FileOutputStream


leaf leaf leaf
grand children of root

RuntimeException
5
leaf great grand child of root
Definition

• A tree t is a finite nonempty set of elements.


• One of these elements is called the root.
• The remaining elements, if any, are
partitioned into trees, which are called the
subtrees of t.

6
Subtrees
Object root

Number Throwable OutputStream

Integer Double Exception FileOutputStream

RuntimeException
7
Leaves
Object

Number Throwable OutputStream

Integer Double Exception FileOutputStream

RuntimeException
8
Parent, Grandparent, Siblings, Ancestors, Descendants

Children of the same


Object parent are called siblings

Number Throwable OutputStream

Integer Double Exception FileOutputStream

RuntimeException
9
Levels
Object Level 1

Level 2
Number Throwable OutputStream

Integer Double Exception FileOutputStream


Level 3

RuntimeException
10
Level 4
Caution

• Some texts start level numbers at 0 rather than


at 1 (e.g. The textbook by Hubbard and Huray)
• We shall number levels as follows:
• Root is at level 1.
• Its children are at level 2.
• The grand children of the root are at level 3.
• And so on.
11
height = depth = highest level number
Height of empty Height of a single-
tree is 0 Object node tree is 1
Level 1
Level 2

Number Throwable OutputStream

Integer Double Exception FileOutputStream


Level 3

RuntimeException
Level 4 12
Node Degree = Number Of Children
Object 3

2 Number 1 Throwable 1 OutputStream

0 0 1 0
Integer Double Exception FileOutputStream

RuntimeException 0
13
Tree Degree = Max Node Degree
Object 3

2 Number 1 Throwable 1 OutputStream

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.

Left Subtree Right Subtree

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

Left node b b Right node

• Are different when viewed as binary trees.


• Are the same when viewed as trees.
18
Tree Implementation

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)

Node (a list of children)

(element) (child node)

20
Structure for a Tree

Try to implement the 



following Tree:
B
B
 

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

ordered pair of children,


each of which is a binary D E F G
tree
H I

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)

def setLeftChild(self, theLeftChild):


self.left = theLeftChild
def setRightChild(self, theRightChild):
self.right = theRightChild
29
BinaryTree.py
Special
Binary Trees

30
Properties
- Full Binary Tree
• A full binary tree of a given height h has
2h – 1 nodes.

Height 4 full binary tree. 31


Numbering Nodes in a Full Binary Tree
• Number the nodes 0 through 2h – 2.
(total 2h – 1 nodes)
• Number by levels from top to bottom.
• Within a level number from left to right.
0

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

Meaning: Each internal node has exactly 2 children

34
Proper Binary Trees
Given the following definitions: Properties:

n :number of total nodes 1. e = i + 1


2. n = i + e = 2e − 1
e :number of external nodes (leaves)
3. h  i + 1 = (n − 1)2
i :number of internal nodes
4. e  2h−1
h :height (maximum depth of a node)
5. h  log2 e + 1
6. h  log2 (n + 1)

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

Binary tree associated with a decision process


 internal nodes: questions with yes/no answer
 external nodes: decisions

Example: dining decision

Want a fast meal?


Yes No

On a diet? On expense account?


No
No Yes
Yes
Subway Mc Donald’s Chinese Eat at Home
38
Restaurant
Traversals of a 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

Gives prefix form of expression! 46


Preorder Traversal

def traversePreorder(self, root):


if root is not None:
print(root.data)
self.traversePreorder(root.left)
self.traversePreorder(root.right)

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

Gives infix form of expression! 53


Inorder Traversal
def traverseInorder(self, root):
if root is not None:
self.traverseInorder(root.left)
print(root.data)
self.traverseInorder(root.right)

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

def traversePostorder(self, root):


if root is not None:
self.traversePostorder(root.left)
self.traversePostorder(root.right)
print(root.data)

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 + /

Gives postfix form of expression! 60


Level order Traversals of a Binary
Tree

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

You might also like