Tree Notes
Tree Notes
data structures
When you first learn to code, it’s common to learn arrays as the
“main data structure.”
Eventually, you will learn about hash tables too. If you are
pursuing a Computer Science degree, you have to take a class on
data structure. You will also learn about linked lists, queues,
and stacks. Those data structures are called “linear” data
structures because they all have a logical start and a logical end.
When we start learning about trees and graphs, it can get really
confusing. We don’t store data in a linear way. Both data structures
store data in a specific way.
This post is to help you better understand the Tree Data Structure
and to clarify any confusion you may have about it.
In this article, we will learn:
• What is a tree
• Examples of trees
• Its terminology and how it works
• How to implement tree structures in code.
Let’s start this learning journey. :)
Definition
When starting out programming, it is common to understand better
the linear data structures than data structures like trees and graphs.
Trees are well-known as a non-linear data structure. They don’t
store data in a linear way. They organize data hierarchically.
TK, Yuji, Bruno, and Kaio are the children of my parents (me and
my brothers).
An organization’s structure is another example of a hierarchy.
A technical definition
A tree is a collection of entities called nodes. Nodes are connected
by edges. Each node contains a value or data, and it may or may
not have a child node .
The first node of the tree is called the root. If this root node is
connected by another node, the root is then a parent node and the
connected node is a child.
Terminology summary
• Root is the topmost node of the tree
• Edge is the link between two nodes
• Child is a node that has a parent node
• Parent is a node that has an edge to a child node
• Leaf is a node that does not have a child node in the tree
• Height is the length of the longest path to a leaf
• Depth is the length of the path to its root
Binary trees
Now we will discuss a specific type of tree. We call it thebinary
tree.
“In computer science, a binary tree is a tree data structure in which each node has at the
most two children, which are referred to as the left child and the right child.”
— Wikipedia
b_node = a_node.left_child
b_node.insert_right('d')
c_node = a_node.right_child
c_node.insert_left('e')
c_node.insert_right('f')
d_node = b_node.right_child
e_node = c_node.left_child
f_node = c_node.right_child
print(a_node.value) # a
print(b_node.value) # b
print(c_node.value) # c
print(d_node.value) # d
print(e_node.value) # e
print(f_node.value) # f
Insertion is done.
Now we have to think about tree traversal.
We have two options here: Depth-First Search
(DFS) and Breadth-First Search (BFS).
• DFS “is an algorithm for traversing or searching tree data
structure. One starts at the root and explores as far as
possible along each branch before backtracking.” — Wikipedia
• BFS “is an algorithm for traversing or searching tree data
structure. It starts at the tree root and explores the neighbor
nodes first, before moving to the next level
neighbors.” — Wikipedia
So let’s dive into each tree traversal type.
Depth-First Search (DFS)
DFS explores a path all the way to a leaf before backtracking and
exploring another path. Let’s take a look at an example with this
type of traversal.
if self.left_child:
self.left_child.pre_order()
if self.right_child:
self.right_child.pre_order()
In-order
The result of the in-order algorithm for this tree example is 3–2–4–
1–6–5–7.
The left first, the middle second, and the right last.
Now let’s code it.
def in_order(self):
if self.left_child:
self.left_child.in_order()
print(self.value)
if self.right_child:
self.right_child.in_order()
1. Go to the left child and print it. This is if, and only if, it has
a left child.
2. Print the node’s value
3. Go to the right child and print it. This is if, and only if, it has
a right child.
Post-order
The result of the post order algorithm for this tree example is 3–
4–2–6–7–5–1.
The left first, the right second, and the middle last.
Let’s code this.
def post_order(self):
if self.left_child:
self.left_child.post_order()
if self.right_child:
self.right_child.post_order()
print(self.value)
1. Go to the left child and print it. This is if, and only if, it has
a left child.
2. Go to the right child and print it. This is if, and only if, it has
a right child.
3. Print the node’s value
Breadth-First Search (BFS)
BFS algorithm traverses the tree level by level and depth by depth.
Here is an example that helps to better explain this algorithm:
if current_node.left_child:
queue.put(current_node.left_child)
if current_node.right_child:
queue.put(current_node.right_child)
To implement a BFS algorithm, we use the queue data structure to
help.
How does it work?
Here’s the explanation.
1. First add the root node into the queue with the put method.
2. Iterate while the queue is not empty.
3. Get the first node in the queue, and then print its value.
4. Add both left and right children into the queue (if the
current nodehas children).
5. Done. We will print the value of each node, level by level, with
our queuehelper.
Binary Search tree
“A Binary Search Tree is sometimes called ordered or sorted binary trees, and it keeps its
values in sorted order, so that lookup and other operations can use the principle of
binary search” — Wikipedia
return True
1. First: Note the parameters value and parent. We want to find
the nodethat has this value , and the node’s parent is
important to the removal of the node.
2. Second: Note the returning value. Our algorithm will return a
boolean value. It returns True if it finds the node and removes
it. Otherwise it will return False.
3. From line 2 to line 9: We start searching for the node that has
the valuethat we are looking for. If the value is smaller than
the current nodevalue , we go to the left subtree,
recursively (if, and only if, the current node has a left
child). If the value is greater, go to the right subtree,
recursively.
4. Line 10: We start to think about the remove algorithm.
5. From line 11 to line 13: We cover the node with no children ,
and it is the left child from its parent. We remove
the node by setting the parent’s left child to None.
6. Lines 14 and 15: We cover the node with no children , and it
is the right child from it’s parent. We remove the node by
setting the parent’s right child to None.
7. Clear node method: I will show the clear_node code below. It
sets the nodes left child , right child, and
its value to None.
8. From line 16 to line 18: We cover the node with just
one child (left child), and it is the left child from
it’s parent. We set the parent's left child to
the node’s left child (the only child it has).
9. From line 19 to line 21: We cover the node with just
one child (left child), and it is the right child from
its parent. We set the parent's right child to
the node’s left child (the only child it has).
10. From line 22 to line 24: We cover the node with just
one child (right child), and it is the left child from
its parent. We set the parent's left child to
the node’s right child (the only child it has).
11. From line 25 to line 27: We cover the node with just
one child (right child) , and it is the right child from
its parent. We set the parent's right child to
the node’s right child (the only child it has).
12. From line 28 to line 30: We cover the node with
both left and rightchildren. We get the node with the
smallest value (the code is shown below) and set it to
the value of the current node . Finish it by removing the
smallest node.
13. Line 32: If we find the node we are looking for, it needs to
return True. From line 11 to line 31, we handle this case. So
just return True and that’s it.
• To use the clear_node method: set the None value to all three
attributes — (value, left_child, and right_child)
def clear_node(self):
self.value = None
self.left_child = None
self.right_child = None
• To use the find_minimum_value method: go way down to the
left. If we can’t find anymore nodes, we found the smallest
one.
def find_minimum_value(self):
if self.left_child:
return self.left_child.find_minimum_value()
else:
return self.value
Now let’s test it.
We will use this tree to test our remove_node algorithm.
# |15|
# / \
# |10| |20|
# / \ / \
# |8| |12| |17| |25|
# \
# |19|
Let’s remove the node with the value 8. It’s a node with no child.
print(bst.remove_node(8, None)) # True
bst.pre_order_traversal()
# |15|
# / \
# |10| |20|
# \ / \
# |12| |17| |25|
# \
# |19|
Now let’s remove the node with the value 17. It’s a node with just
one child.
print(bst.remove_node(17, None)) # True
bst.pre_order_traversal()
# |15|
# / \
# |10| |20|
# \ / \
# |12| |19| |25|
Finally, we will remove a node with two children. This is the root of
our tree.
print(bst.remove_node(15, None)) # True
bst.pre_order_traversal()
# |19|
# / \
# |10| |20|
# \ \
# |12| |25|
The tests are now done. :)
Additional resources
• Introduction to Tree Data Structure by mycodeschool
• Tree by Wikipedia
• How To Not Be Stumped By Trees by the talented Vaidehi
Joshi
• Intro to Trees, Lecture by Professor Jonathan Cohen
• Intro to Trees, Lecture by Professor David Schmidt
• Intro to Trees, Lecture by Professor Victor Adamchik
• Trees with Gayle Laakmann McDowell
• Binary Tree Implementation and Tests by TK
• Coursera Course: Data Structures by University of
California, San Diego
• Coursera Course: Data Structures and Performance
by University of California, San Diego
• Binary Search Tree concepts and Implementation by Paul
Programming
• Binary Search Tree Implementation and Tests by TK
• Tree Traversal by Wikipedia
• Binary Search Tree Remove Node Algorithm
by GeeksforGeeks
• Binary Search Tree Remove Node Algorithm by Algolist
• Learning Python From Zero to Hero