Trees

Introduction to Trees
Computer Science 4
Reference:
Objective: Understand Concepts related to trees.
What is a Binary Tree?
• Recall that in a linked list each node
contains a link to another similar node.
• In a binary tree, each node contains a link to
two other similar nodes.
• This leads to a linked data structure that
“branches”.
A Binary tree
B
G
O
W
D
T
A
U
3
Some Terms
• Every binary tree has a node at the “top”.
– No other node references it.
– This is called the root node.
• Every binary tree has nodes where both
references are null.
– I.e. it does not point to any lower nodes
– These are called leaf nodes.
Root Node
B
G
O
W
D
T
A
U
5
Leaf Nodes
B
G
O
W
D
T
A
U
6
Subtrees
• The references contained in a binary tree node are
traditionally called the left and right childern.
• Each node can be said to have a left and right
subtree
– Left subtree the left child and all its descendents.
– Right subtree includes the right child and all its
descendants
• Note that a subtree (like any binary tree) may be
empty.
Node B’s left subtree
B
G
O
W
D
T
A
U
8
Node B’s right subtree
B
G
O
W
D
T
A
U
9
Some More Terms
• The distance between a node and the root node is called
its level
– Note that this makes the root node level 0
• The maximum level in a tree is called its height.
• The maximum number of nodes on level L
– 1 for 0, 2 for 1, 4 for 2, 8 for 3, 16 for 4
– In general 2L.
• The maximum number of nodes in a tree of height H
– 1 for 0, 3 for 1, 7 for 2, 15 for 3
– In general, is 2H+1-1
This tree’s height is 3
Level
0
B
1
2
3
G
O
W
D
T
A
U
11
Parent and Child Nodes
• When nodeA points to nodeB, we say
– NodeA is nodeB’s parent
– NodeB is nodeA’s child
• When nodeA is above nodeC in the tree, we
say
– NodeA is an ancestor of NodeC
– NodeC is a descendant of NodeA
Node O is the parent of Node A
B
G
O
W
D
T
A
U
13
Node O is the child of Node B
B
G
O
W
D
T
A
U
14
Node T is a descendant of node G
B
G
O
W
D
T
A
U
15
Node B is an ancestor of node W
B
G
O
W
D
T
A
U
16
Minimum Height of a Binary
Tree
• The maximum number of nodes in a binary tree of
height H is 2H+1-1
• Based on this, what’s the minimum number of levels of
a tree containing N nodes.
–
–
–
–
–
If N is 20 (1), need 0 levels.
If N is 21 (2), need 1 level.
If N is 22 (4), need 2 levels.
If N is 23 (1), need 3 levels.
If N is 2p, need P levels.
• Therefore need Floor(Log2N) levels to store N nodes.
Summary
• Each node in a binary contains references to two
other nodes.
• Root node at the top of the tree
• Leaf nodes don’t reference any other nodes
• Height of the tree is the number of levels
• Parents and children, ancestors and descendants.
• Can store 2L nodes on level L
• Minimum height of a tree with N items is Log2N