SlideShare a Scribd company logo
1 of 131
Trees
Eleonora Ciceri, Politecnico di Milano
Email: eleonora.ciceri@polimi.it
Definition: Graph
Graph
ī‚¤ Graph: set of elements (nodes) connected with lines (edges)
ī‚¤ G = (V,E)
ī‚¤ V: set of nodes
ī‚¤ E: set of edges such that an element in E connects a pair of
elements in V
V = (1,2,3,4,5)
E = (a,b,c,d)
1
2
3
4
5
a
b
c
d
Graph
ī‚¤ Graph types
ī‚¤ Directed graph: graph in which edges are characterized by a
direction(from node A to node B)
ī‚¤ Undirected graph: graph which does not contain directed edges;
if an edge is drawn from node A to node B, it means that we can
move both from A to B and from B to A
ī‚¤ Famous examples of graphs
ī‚¤ Social networks (nodes: users; edges: friendship)
ī‚¤ Computer networks (nodes: computers; edges: physical
connections)
ī‚¤ Transportation networks(nodes: cities; edges: routes)
Structureofasocial
network
from: Wikipedia, the free encyclopedia, Social graph
Some definition
Connected components
Clique
Trees
What is a tree?
ī‚¤ Tree: plant characterized by a
trunk with branches in the
upper part, called foliage
root
leaves
branch
What is a tree?
ī‚¤ Tree: undirected graph in
which two nodes are
connected by one and
only one path
ī‚¤ Node: contains some
data
ī‚¤ Edge: specifies a
hierarchical
connection between
nodes
root
leaves
branch
What is a tree?
ī‚¤ Tree: undirected graph in
which two nodes are
connected by one and
only one path
ī‚¤ Node: contains some
data
ī‚¤ Edge: specifies a
hierarchical
connection between
nodes
root
leaves
branchpath
What is a tree?
ī‚¤ Tree: undirected graph in
which two nodes are
connected by one and
only one path
ī‚¤ Node: contains some
data
ī‚¤ Edge: specifies a
hierarchical
connection between
nodes
root
leaves
branchpath
A tree is acyclic
There does not exist any alternative
path to go from node A to node B
Using trees
ī‚¤ When do you use trees?
ī‚¤ To represent hierarchical data
ī‚¤ To rapidly look for objects
ī‚¤ To represent decision flows
ī‚¤ To represent object orderings
Answer A Answer B
Decision tree Tree of possible orderings
Using trees
ī‚¤ Video phylogeny: trace a document’s copy process on the
Web, e.g., when it is protected by copyright laws
Similarity
relationships
Tree components
Tree components
root
leaves
branch
Tree components:
Root node
ī‚¤ It is strictly required that a tree contains a unique node which
does not have incoming edges
ī‚¤ This node is called root node
ī‚¤ There does not exist a tree without a root node
Tree components:
Leaf node
ī‚¤ Every node which does not have outgoing edges is called leaf
node
ī‚¤ Every finite tree (i.e., which contains a finite number of nodes)
there exists at least a leaf node
Tree components:
Edges
ī‚¤ An edge (or: branch) defines a hierarchical connection
between nodes
A parent node is a node with
an outgoing edge
i.e., the parent node is higher than
a child node
Tree components:
Edges
A child node is a node with an
incoming edge
i.e., a child node is lower than its
parent node
ī‚¤ An edge (or: branch) defines a hierarchical connection
between nodes
Tree components:
Nodes and edges
ī‚¤ A node can be a parent node and a child node at the same time,
and this happens if it has both incoming edges and outgoing
edges
ī‚¤ In this case the node is called internal node
ī‚¤ An internal node is not a leaf node
Root
Parent of
Parent of
Child of Root
Father of
Child of
Leaf
Child of
The root does not have a parent
A leaf does not have children
Balanced and unbalanced trees
ī‚¤ The leaves could be positioned at different levels; their
positioning defines the tree balancing property
ī‚¤ If leaves are position “closely” (e.g., at maximum a single level
separates them) then the tree is balanced
Tree (perfectly) balanced Unbalanced tree
Definitions
ī‚¤ Node height: length of the longest path between the node and
a leaf
ī‚¤ Node depth: length of path from the node and the tree root
Height
Depth
Definitions
ī‚¤ Sub-tree of a tree T: tree consisting in a node n belonging to tree
T, together with all its descendants in T
ī‚¤ The sub-tree corresponding to the root T is the whole tree T
Binary trees
Binary tree vs. N-ary tree
ī‚¤ A binary tree is a tree whose nodes can have two children at
maximum
ī‚¤ An n-ary tree is a tree where there does not exist a limit on the
number of children a node could have
Binary complete trees vs. Binary
incomplete trees
ī‚¤ A tree is complete if it is a binary tree and:
ī‚¤ Each level (except the last) is full of nodes
ī‚¤ The nodes are at the leftmost positions
ī‚¤ The last level may contain few nodes, but it has to be filled
from left to right
Complete tree Incomplete tree
Binary tree: from concept to
implementation
ī‚¤ We are going to store the tree as a dynamic data structure
ī‚¤ Ideas?
Binary tree: from concept to
implementation
ī‚¤ We are going to store the tree as a dynamic data structure
ī‚¤ How to position them?
Ingredients What to represent
Struct
Pointers
Nodes
Edges
Binary tree: from concept to
implementation
Ingredients What to represent
Struct
Pointers
Nodes
Edges
ī‚¤ We are going to store the tree as a dynamic data structure
ī‚¤ We’ll use the same principles used with linked lists:
Binary tree: Structure
ī‚¤ Each node in a binary tree contains:
ī‚¤ A left pointer
ī‚¤ A right pointer
ī‚¤ Data
ī‚¤ The pointers in the node point recursively at two sub-trees
(i.e., smaller trees) positioned on its left side and right side
Left
Sub-tree
Right
Sub-tree
Left
Sub-tree
Right
Sub-Tree
Binary tree: Structure
ī‚¤ We’ll see then a node as follows:
ī‚¤ Note. Since the node structure is dynamic, we have to be very
careful in handling the pointer to the root: if we lose it, we lose
every possibility of accessing to the tree!
Data contained in
the node
Left sub-tree Right sub-tree
Binary tree: Structure
2
7 8
2 9 3 1
Binary tree: Structure
2
7 8
2 9 3 1
The root is pointed to by a
“head” pointer
Binary tree: Structure
2
7 8
2 9 3 1
Leaves have left and right
pointers set to null
Incomplete binary tree
ī‚¤ Internal nodes do not have necessarily both left and right
children, some of them may be null
2
7 8
9 3
2
7 8
3 1
Manual creation of a binary tree
Binary tree: manual creation
1
rootNode
2 3
leftChild rightChild
4
leftChild2
5
rightChild2
rightChild2->data = 5;
rightChild2->leftPtr = NULL;
rightChild2->rightPtr = NULL;
Binary tree: manual creation
1
rootNode
2 3
leftChild rightChild
4
leftChild2
5
rightChild2
rootNode->leftPtr = leftChild;
rootNode->rightPtr = rightChild;
Binary tree: manual creation
1
rootNode
2 3
leftChild rightChild
4
leftChild2
5
rightChild2
leftChild->leftPtr = leftChild2;
leftChild->rightPtr = rightChild2;
Counting nodes
Counting nodes
ī‚¤ Aim: counting the number of nodes in the tree
ī‚¤ The approach we propose for any algorithm involving tree
manipulation is recursive. Thus, it is necessary to define:
ī‚¤ A base case
ī‚¤ A recursion step
ī‚¤ Hint: always look for base case in the leaves of the treeâ€Ļ
Counting nodes
1+ nodes-left + nodes-right 1+ nodes-left + nodes-right
1+ nodes-left + nodes-right
To visit the child nodes of n,
we visit first its left sub-tree
and then its right sub-tree
Given a node n, we count the number of
nodes in the sub-tree having n as root
as:
1 + “the number of child nodes
on the left” + “the number of
child nodes on the right”
Counting nodes
1+ nodes-left + nodes-right
1+ nodes-left + nodes-right
1+ nodes-left + nodes-right
=
0
=
0
1+ nodes-left + nodes-right
1+ 1 + nodes-right
When we reach a leaf, we go back to its
parent node
īƒŧ If we were visiting the left sub-tree,
we move to the right sub-tree
Counting nodes
1+ nodes-left + nodes-right
1+ 1 + nodes-right
1+ nodes-left + nodes-right
=
0
1+ nodes-left + nodes-right
1+ 1 + nodes-right
1+ 0 + nodes-right
=
0
1+ nodes-left + nodes-right
=
0
Counting nodes
1+ nodes-left + nodes-right
1+ 1 + nodes-right
1+ 0 + 1
1+ nodes-left + nodes-right
1+ 1 + 2
Counting nodes
1+ 4 + nodes-right 1+ 4 + nodes-right
1+ nodes-left + nodes-right
1+ 4 + nodes-right
1+ 0+ nodes-right
1+ nodes-left + nodes-right
=
0
=
0
=
0
Counting nodes
1+ 4 + nodes-right
1+ 0 + 1
1+ 4 + 2
Node count = 7
Counting nodes
ī‚¤ The proposed procedure is, again, recursive
ī‚¤ When we reach a node (any node):
ī‚¤ We add +1 to count the current node
ī‚¤ We ask to count nodes in the left sub-tree
ī‚¤ We ask to count nodes in the right sub-tree
ī‚¤ The base case is on a null pointer (i.e., a “missing” left sub-tree
or right sub-tree). It is NOT a node:
ī‚¤ It does not have left children
ī‚¤ It does not have right children
ī‚¤ Its contribution to the total count is 0
Counting nodes
ī‚¤ Question: while performing the recursive calls, do the pointers
to the nodes have to be passed by copy or by reference?
Counting nodes
ī‚¤ Question: while performing the recursive calls, do the pointers
to the nodes have to be passed by copy or by reference?
Do I have to propagate any updates to the pointer when I
return from the recursive call execution?
Counting nodes
ī‚¤ Question: while performing the recursive calls, do the pointers
to the nodes have to be passed by copy or by reference?
Do I have to propagate any updates to the pointer when I
return from the recursive call execution?
Do I need to change the tree structure?
Counting nodes
ī‚¤ Answer: counting nodes does not have to change the tree
structure
ī‚¤ If I passed any pointer by reference, and it was modified by the
function, it would update the pointer in the caller, changing the
structure of the tree (“where is the root of the tree now?”)
Counting nodes
Pointer to the current node
Base case
Recursive step
Computing tree height
Computing tree height
ī‚¤ Tree height: length of the longest path between the root and a
leaf
Height
Computing tree height
ī‚¤ The common trick to write correctly tree manipulation functions
is to understand which are the base case and the recursion
step
ī‚¤ The base case is usually set on the leaves of the tree
ī‚¤ Which is the right approach to compute tree height?
Computing tree height
ī‚¤ The common trick to write correctly tree manipulation functions
is to understand which are the base case and the recursion
step
ī‚¤ The base case is usually set on the leaves of the tree
ī‚¤ Which is the right approach to compute tree height?
ī‚¤ Base case: if the current pointer is NULL, it means we are at the
“end” (lower end) of the tree. Thus, the current height is 0 (we are
at the base of the tree)
Height
Computing tree height
ī‚¤ The common trick to write correctly tree manipulation functions
is to understand which are the base case and the recursion
step
ī‚¤ The base case is usually set on the leaves of the tree
ī‚¤ Which is the right approach to compute tree height?
ī‚¤ Base case: if the current pointer is NULL, it means we are at the
“end” (lower end) of the tree. Thus, the current height is 0 (we are
at the base of the tree)
ī‚¤ Generic case: if the current pointer is NULL, the current node’s
height is 1 + the height of its chidren
Height
Computing tree height
Base
Height with respect to
the base: 0
Height (with respect to
the base): 1
Height (with respect to
the base): 2
Height (with respect to
the base): 3
Computing tree height
My child’s height: 0
My height: 1+0 = 1
My child’s height: 1
My height: 1+1 = 2
My left child’s height: 1
My right child’s height: 2
My height: 1+max(1,2) = 3
Base
Height with respect to
the base: 0
Height (with respect to
the base): 1
Height (with respect to
the base): 2
Height (with respect to
the base): 3
Computing tree height
Height of sub-tree having root
leftPtr
Height of sub-tree having root
rightPtr
Element search in the tree
Element search in the tree
ī‚¤ Element search returns:
ī‚¤ NULL if the element is not in the tree
ī‚¤ A pointer to the node that contains the element, if the element is in
the tree
ī‚¤ The tree is not ordered. Thus, given a node, the element that
we are looking for could be:
ī‚¤ The current node
ī‚¤ A node in the left sub-tree
ī‚¤ A node in the right sub-tree
ī‚¤ â€Ļnot present, too!
Element search in the tree
ī‚¤ We will return currentNode ifâ€Ļ?
Element search in the tree
ī‚¤ We will return currentNode if:
ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we
did not find anything along the path we followed)
ī‚¤ currentNode contains the element (i.e., the search is done)
Element search in the tree
ī‚¤ We will return currentNode if:
ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we
did not find anything along the path we followed)
ī‚¤ currentNode contains the element (i.e., the search is done)
ī‚¤ In case currentNode is not NULL and not containing the
element we want to findâ€Ļ?
Element search in the tree
ī‚¤ We will return currentNode if:
ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we
did not find anything along the path we followed)
ī‚¤ currentNode contains the element (i.e., the search is done)
ī‚¤ In case currentNode is not NULL and not containing the
element we want to find:
ī‚¤ We look for the element in the left sub-tree. If the element is here,
I’ll return it
ī‚¤ If the element is NOT in the left sub-tree, I’ll return the result of the
search in the right sub-tree
ī‚¤ Either the element, if present, or NULL
Element search in the tree
Element search in the tree
Equivalentlyâ€Ļ
Printing tree nodes
AKA: how to merge linked lists and binary trees
Printing tree nodes
ī‚¤ Paths in the tree may have different lengths
ī‚¤ Approach:
ī‚¤ navigate the tree first at the left side, then at the right side
ī‚¤ store each path in a linked list
ī‚¤ when we reach a leaf, the path is as its end, thus we can print it
(i.e., we print the content of the linked list)
1
2 3
4 5
Printing tree nodes
1 2 4
1 2 5
1 3
1
2 3
4 5
Printing tree nodes
ī‚¤ How do we print paths?
ī‚¤ That is:
ī‚¤ How do we navigate through the tree so as to visit every path, one
after another?
ī‚¤ How to store a path in a linked list?
Printing tree nodes
ī‚¤ How do we navigate through the tree so as to visit every
path, one after another?
ī‚¤ We visit the tree by traversing the left sub-trees first and the right
sub-trees after
ī‚¤ This is similar to what happened with the nodes printing procedure
ī‚¤ How to store a path in a linked list?
ī‚¤ At first, we initialize the list as an empty list
ī‚¤ As we visit nodes along a path, we attach those nodes in the list
ī‚¤ On the head? On the tail?
Printing tree nodes
ī‚¤ How do we navigate through the tree so as to visit every
path, one after another?
ī‚¤ We visit the tree by traversing the left sub-trees first and the right sub-
trees after
ī‚¤ This is similar to what happened with the nodes printing procedure
ī‚¤ How to store a path in a linked list?
ī‚¤ At first, we initialize the list as an empty list
ī‚¤ As we visit nodes along a path, we attach those nodes in the list
ī‚¤ On the tail, otherwise we will print the path in the wrong direction!
Printing tree nodes: initializing the linked
list
ī‚¤ In printPaths():
ī‚¤ We initialize the list head
ī‚¤ We initialize the list tail
ī‚¤ We start the tree printing procedure
1
2 3
4 5
rootNode
pathHead
pathTail
overload
Printing tree nodes
1
2 3
4 5
rootNode
At first we print this
pathâ€Ļ 1
2 3
4 5
rootNode
â€Ļthen this one.
1
2 3
4 5
rootNode
We go to the left
sub-treeâ€Ļ
1
2 3
4 5
rootNode
â€Ļand again to
the left sub-tree.
We are at a leaf:
we print the list
Printing tree nodes
1
2 3
4 5
rootNode
1
2 3
4 5
rootNode
1
2 3
4 5
rootNode To print this path we go
back to the rootâ€Ļ
1
2 3
4 5
rootNode
â€Ļand we go to
the right child.
We are at a leaf:
we can print the
list.
We go back to
the parentâ€Ļ
â€Ļand then to the right child.
We are at a leaf: we print the
list
Printing tree nodes
ī‚¤ We insert the root in the list: 1
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2 4
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 2 5
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We remove the left child from the list: 1
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 3
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1
ī‚¤ We remove the root from the list:
1
2 3
4 5
ī‚¤ We insert the root in the list: 1
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2 4
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 2 5
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We remove the left child from the list: 1
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 3
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1
ī‚¤ We remove the root from the list:
Printing tree nodes
First
level
1
2 3
4 5
ī‚¤ We insert the root in the list: 1
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2 4
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 2 5
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We remove the left child from the list: 1
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 3
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1
ī‚¤ We remove the root from the list:
Printing tree nodes
Second
level
1
2 3
4 5
ī‚¤ We insert the root in the list: 1
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2
ī‚¤ We require to print the left child
ī‚¤ We insert the left child in the list: 1 2 4
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 2 5
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1 2
ī‚¤ We remove the left child from the list: 1
ī‚¤ We require to print the right child
ī‚¤ We insert the right child in the list: 1 3
ī‚¤ We are at a leaf: we print the list
ī‚¤ We remove the leaf node from the list: 1
ī‚¤ We remove the root from the list:
Printing tree nodes
Base case: leaf node
1
2 3
4 5
Printing tree nodes
ī‚¤ The procedure is recursive
ī‚¤ When we reach a node
ī‚¤ We add its content to the list
ī‚¤ We ask to print the left tree
ī‚¤ We ask to print the right tree
ī‚¤ We remove its content from the list
ī‚¤ Base case: on the leaf
ī‚¤ We insert its content in the list
ī‚¤ We ask to print the path from the root to that leaf
ī‚¤ We remove its content from the list
Printing tree nodes
Printing tree nodes
First case: empty list
I have to add the root to the list
īƒŧ pathHead = NULL
īƒŧ pathTail = NULL
newNode
Printing tree nodes
newNode
pathHead
pathTail
First case: empty list
I have to add the root to the list
īƒŧ pathHead = NULL
īƒŧ pathTail = NULL
Printing tree nodes
Second case: non-empty list
We add either a leaf node or an internal node to the
list
newNode
pathHead
pathTail
Printing tree nodes
newNode
pathHead
pathTail
Second case: non-empty list
We add either a leaf node or an internal node to the
list
Printing tree nodes
Printing tree nodes
Base case: leaf
Printing tree nodes
Generic case:
either internal
nodes or root node
Printing tree nodes
Additional notes on trees
Graph
ī‚¤ A graph is a set of nodes connected via edges
ī‚¤ It is usually represented as G(V,E), where:
ī‚¤ V is the set of nodes
ī‚¤ E is the set of edges
ī‚¤ Trees vs. graphs
ī‚¤ A tree has a unique root, while the graph could have multiple roots
ī‚¤ Tree nodes have just an incoming edge, while graph edges could
have multiple incoming edges
N-ary trees
ī‚¤ Generalization of binary trees
ī‚¤ Every node could have an arbitrary number of children
ī‚¤ It is generally used to represent hierarchical structures (e.g.,
company employees hierarchy)
Exercises
Counting leaf and non-leaf nodes
ī‚¤ Write:
ī‚¤ A function that counts the number of leaf nodes
ī‚¤ A function that counts the number of non-leaf nodes
Counting leaf and non-leaf nodes
ī‚¤ A leaf node is a node without children
ī‚¤ leftPtr is NULL
ī‚¤ rightPtr is NULL
ī‚¤ The non-leaf nodes (called internal nodes) areâ€Ļ all the other
nodes!
non_leaf_nodes = total_nodes – leaf_nodes
Counting leaf and non-leaf nodes
Counting nodes on even levels
ī‚¤ Write a function that counts the number of nodes on even
levels of the tree
ī‚¤ Even levels are the ones having even ID
Level 1
Level 2
Level 3
Level 4
Counting nodes on even levels
ī‚¤ We keep track of the current depth with an integer
ī‚¤ depth = 1 is we are on the root
ī‚¤ depth = 2 if we are on the root’s children
ī‚¤ â€Ļ
ī‚¤ If dividing depth by 2 has null reminder, then we add 1 to the
count of nodes on even levels
Counting nodes on even levels
Equal trees
ī‚¤ Write a function that, given two trees, returns
ī‚¤ true if the trees are identical
ī‚¤ false if the trees are not identical
Equal trees
ī‚¤ Given a node n and a node m, the sub-trees having n and m as
root are identical if:
ī‚¤ n and m contain the same value
ī‚¤ The sub-trees having n->leftPtr and m->leftPtr as root are
identical
ī‚¤ The sub-trees having n->rightPtr and m->rightPtr as root
are identical
Equal trees
Tree depth
ī‚¤ Write a function that checks whether all the paths have equal
length
Tree depth
Sum of leaf nodes (1)
ī‚¤ Write a function that provides the sum of leaf nodes
Sum of leaf nodes (1)
Sum of leaf nodes (2)
ī‚¤ Assume that every path is associated with a score, which can
be computed by summing the node values along that path.
Thus, if the tree contains N paths, it contains N scores too (one
for each path)
ī‚¤ Write a function that returns the highest score
Sum of leaf nodes (2)
Sum of leaf nodes(2) (alternative
solution)
Serialize leaves
ī‚¤ Write a function that extracts all the leaves from the tree and
builds a linked list, in which each node represents one of the
leaves of the tree
Serialize leaves
We go down
at the left
We go back and
go down at the
right
We go back and
go down at the
right
Serialize leaves
Ordered tree insertion
ī‚¤ Write a function that, given a vector<string> as an
input,inserts the words in a tree in an ordered manner: for
every node n in the tree, every word in the left sub-tree come
before the word in n alphabetically, while all the others are in
the right sub-tree
Vector: dog, cat, horse, alpaca, bee, shark, fox, mosquito, sheep
Ordered tree insertion
ī‚¤ For each word from the vector:
ī‚¤ If it precedes the word contained in the current node, it has to go
down in the left sub-tree
ī‚¤ If it follows the word contained in the current node, it has to go
down in the right sub-tree
cat < dog
horse > dog alpaca < dog
alpaca < cat
Ordered tree insertion
For each elementâ€Ļ
â€Ļwe verify its position and insert it as a
leaf
Ordered tree insertion
Ordered tree insertion
Even or odd levels?
ī‚¤ Write a function that returns true if every number contained in
the even levels are even and every number in the odd levels
are odd, or false otherwise
Even or odd levels?
Equal sum on trees
ī‚¤ Write a function that, given two binary trees, returns true if:
ī‚¤ The sum of the leaves of the two trees is equal
ī‚¤ OR
ī‚¤ The first tree has at least a leaf whose value is equal to the sum of
the values in the leaves of the second tree
ī‚¤ or false otherwise
Equal sum on trees
Equal sum on trees
Equal sum on trees
The mirror
ī‚¤ Change a tree in its mirrored version
The mirror
ī‚¤ Mirroring the tree means that:
ī‚¤ What is on the left has to go on the right
ī‚¤ What is on the right has to go on the left
ī‚¤ We are building a new tree, thus every time we return the
pointer to the new node
ī‚¤ Behavior:
ī‚¤ What to do when the pointer is NULL?
ī‚¤ What to do on the nodes?
The mirror
ī‚¤ Mirroring the tree means that:
ī‚¤ What is on the left has to go on the right
ī‚¤ What is on the right has to go on the left
ī‚¤ We are building a new tree, thus every time we return the
pointer to the new node
ī‚¤ Behavior:
ī‚¤ When the pointer is NULL: we return NULL (nothing has to be
created)
ī‚¤ On the nodes: we return the current node and its sub-trees, which
are swapped
The mirror
References
References
ī‚¤ Alberi: http://it.wikipedia.org/wiki/Albero_(informatica)
ī‚¤ http://www.di.unisa.it/~demarco/sd/lezioni/lezione11.pdf

More Related Content

What's hot

Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsAakash deep Singhal
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data StructureAshim Lamichhane
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
Mca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphMca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphRai University
 
Programming in python - Week 3
Programming in python - Week 3Programming in python - Week 3
Programming in python - Week 3Priya Nayak
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceTransweb Global Inc
 
Lecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsLecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsAakash deep Singhal
 

What's hot (16)

Lecture4
Lecture4Lecture4
Lecture4
 
Lecture3
Lecture3Lecture3
Lecture3
 
Data structure
 Data structure Data structure
Data structure
 
Lecture2
Lecture2Lecture2
Lecture2
 
linked_lists
linked_listslinked_lists
linked_lists
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithms
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Mca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graphMca iii dfs u-4 tree and graph
Mca iii dfs u-4 tree and graph
 
Programming in python - Week 3
Programming in python - Week 3Programming in python - Week 3
Programming in python - Week 3
 
Binary tree
Binary treeBinary tree
Binary tree
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer Science
 
Lecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsLecture 5 data structures and algorithms
Lecture 5 data structures and algorithms
 

Viewers also liked

HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introductionEleonora Ciceri
 
Pasos para subir archivos al Slideshare
Pasos para subir archivos al SlidesharePasos para subir archivos al Slideshare
Pasos para subir archivos al Slidesharedennysguerrero
 
Dont Know Refused
Dont Know RefusedDont Know Refused
Dont Know RefusedSusan Walker
 
EMB Senior CALS Honors Thesis
EMB Senior CALS Honors ThesisEMB Senior CALS Honors Thesis
EMB Senior CALS Honors ThesisEmily Baumann
 
La asociaciÃŗn marquitas que te veo os invita a la
La asociaciÃŗn marquitas que te veo os invita a laLa asociaciÃŗn marquitas que te veo os invita a la
La asociaciÃŗn marquitas que te veo os invita a lavirginiasiteparecebien
 
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015HRwijs
 

Viewers also liked (9)

HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introduction
 
Creacion de una presentacion
Creacion de una presentacionCreacion de una presentacion
Creacion de una presentacion
 
Pasos para subir archivos al Slideshare
Pasos para subir archivos al SlidesharePasos para subir archivos al Slideshare
Pasos para subir archivos al Slideshare
 
Dos ranas
Dos ranasDos ranas
Dos ranas
 
Dont Know Refused
Dont Know RefusedDont Know Refused
Dont Know Refused
 
EMB Senior CALS Honors Thesis
EMB Senior CALS Honors ThesisEMB Senior CALS Honors Thesis
EMB Senior CALS Honors Thesis
 
La asociaciÃŗn marquitas que te veo os invita a la
La asociaciÃŗn marquitas que te veo os invita a laLa asociaciÃŗn marquitas que te veo os invita a la
La asociaciÃŗn marquitas que te veo os invita a la
 
Manual balay microondas 3wg365bic
Manual balay   microondas 3wg365bicManual balay   microondas 3wg365bic
Manual balay microondas 3wg365bic
 
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015
Presentatie HRwijs inspiratiesessie verzuimbeleid 17 09 2015
 

Similar to Trees

NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxRajitha Reddy Alugati
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptxAbirami A
 
Data structure using c module 2
Data structure using c module 2Data structure using c module 2
Data structure using c module 2smruti sarangi
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationnakulvarshney371
 
Binary tree
Binary treeBinary tree
Binary treeRajendran
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search treeMuhazzab Chouhadry
 
trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
Describe the tree data structure- What is a root node- What is a child.docx
Describe the tree data structure- What is a root node- What is a child.docxDescribe the tree data structure- What is a root node- What is a child.docx
Describe the tree data structure- What is a root node- What is a child.docxandyb37
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 treesVictor Palmar
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data StructureOm Prakash
 

Similar to Trees (20)

NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
Data structure using c module 2
Data structure using c module 2Data structure using c module 2
Data structure using c module 2
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Binary tree
Binary treeBinary tree
Binary tree
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Describe the tree data structure- What is a root node- What is a child.docx
Describe the tree data structure- What is a root node- What is a child.docxDescribe the tree data structure- What is a root node- What is a child.docx
Describe the tree data structure- What is a root node- What is a child.docx
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 trees
 
Unit 5 Tree.pptx
Unit 5 Tree.pptxUnit 5 Tree.pptx
Unit 5 Tree.pptx
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Trees
TreesTrees
Trees
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Trees
TreesTrees
Trees
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 

More from Eleonora Ciceri

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfEleonora Ciceri
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfEleonora Ciceri
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfEleonora Ciceri
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfEleonora Ciceri
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfEleonora Ciceri
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfEleonora Ciceri
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithmsEleonora Ciceri
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - ExercisesEleonora Ciceri
 
Doubly Linked Lists
Doubly Linked ListsDoubly Linked Lists
Doubly Linked ListsEleonora Ciceri
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introductionEleonora Ciceri
 
Client side scripting
Client side scriptingClient side scripting
Client side scriptingEleonora Ciceri
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorEleonora Ciceri
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch frameworkEleonora Ciceri
 

More from Eleonora Ciceri (16)

DDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdfDDD - 5 - Domain Driven Design_ Repositories.pdf
DDD - 5 - Domain Driven Design_ Repositories.pdf
 
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdfDDD - 4 - Domain Driven Design_ Architectural patterns.pdf
DDD - 4 - Domain Driven Design_ Architectural patterns.pdf
 
DDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdfDDD - 3 - Domain Driven Design: Event sourcing.pdf
DDD - 3 - Domain Driven Design: Event sourcing.pdf
 
DDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdfDDD - 2 - Domain Driven Design: Tactical design.pdf
DDD - 2 - Domain Driven Design: Tactical design.pdf
 
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdfDDD - 1 - A gentle introduction to Domain Driven Design.pdf
DDD - 1 - A gentle introduction to Domain Driven Design.pdf
 
Artificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdfArtificial Intelligence: an introduction.pdf
Artificial Intelligence: an introduction.pdf
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
 
Doubly Linked Lists
Doubly Linked ListsDoubly Linked Lists
Doubly Linked Lists
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Client side scripting
Client side scriptingClient side scripting
Client side scripting
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Multimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User BehaviorMultimedia Information Retrieval and User Behavior
Multimedia Information Retrieval and User Behavior
 
The CrowdSearch framework
The CrowdSearch frameworkThe CrowdSearch framework
The CrowdSearch framework
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...gurkirankumar98700
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SE...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑đŸŊ‍❤ī¸â€đŸ§‘đŸģ 89...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡ī¸ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 

Trees

  • 1. Trees Eleonora Ciceri, Politecnico di Milano Email: eleonora.ciceri@polimi.it
  • 3. Graph ī‚¤ Graph: set of elements (nodes) connected with lines (edges) ī‚¤ G = (V,E) ī‚¤ V: set of nodes ī‚¤ E: set of edges such that an element in E connects a pair of elements in V V = (1,2,3,4,5) E = (a,b,c,d) 1 2 3 4 5 a b c d
  • 4. Graph ī‚¤ Graph types ī‚¤ Directed graph: graph in which edges are characterized by a direction(from node A to node B) ī‚¤ Undirected graph: graph which does not contain directed edges; if an edge is drawn from node A to node B, it means that we can move both from A to B and from B to A ī‚¤ Famous examples of graphs ī‚¤ Social networks (nodes: users; edges: friendship) ī‚¤ Computer networks (nodes: computers; edges: physical connections) ī‚¤ Transportation networks(nodes: cities; edges: routes)
  • 5. Structureofasocial network from: Wikipedia, the free encyclopedia, Social graph Some definition Connected components Clique
  • 7. What is a tree? ī‚¤ Tree: plant characterized by a trunk with branches in the upper part, called foliage root leaves branch
  • 8. What is a tree? ī‚¤ Tree: undirected graph in which two nodes are connected by one and only one path ī‚¤ Node: contains some data ī‚¤ Edge: specifies a hierarchical connection between nodes root leaves branch
  • 9. What is a tree? ī‚¤ Tree: undirected graph in which two nodes are connected by one and only one path ī‚¤ Node: contains some data ī‚¤ Edge: specifies a hierarchical connection between nodes root leaves branchpath
  • 10. What is a tree? ī‚¤ Tree: undirected graph in which two nodes are connected by one and only one path ī‚¤ Node: contains some data ī‚¤ Edge: specifies a hierarchical connection between nodes root leaves branchpath A tree is acyclic There does not exist any alternative path to go from node A to node B
  • 11. Using trees ī‚¤ When do you use trees? ī‚¤ To represent hierarchical data ī‚¤ To rapidly look for objects ī‚¤ To represent decision flows ī‚¤ To represent object orderings Answer A Answer B Decision tree Tree of possible orderings
  • 12. Using trees ī‚¤ Video phylogeny: trace a document’s copy process on the Web, e.g., when it is protected by copyright laws Similarity relationships
  • 15. Tree components: Root node ī‚¤ It is strictly required that a tree contains a unique node which does not have incoming edges ī‚¤ This node is called root node ī‚¤ There does not exist a tree without a root node
  • 16. Tree components: Leaf node ī‚¤ Every node which does not have outgoing edges is called leaf node ī‚¤ Every finite tree (i.e., which contains a finite number of nodes) there exists at least a leaf node
  • 17. Tree components: Edges ī‚¤ An edge (or: branch) defines a hierarchical connection between nodes A parent node is a node with an outgoing edge i.e., the parent node is higher than a child node
  • 18. Tree components: Edges A child node is a node with an incoming edge i.e., a child node is lower than its parent node ī‚¤ An edge (or: branch) defines a hierarchical connection between nodes
  • 19. Tree components: Nodes and edges ī‚¤ A node can be a parent node and a child node at the same time, and this happens if it has both incoming edges and outgoing edges ī‚¤ In this case the node is called internal node ī‚¤ An internal node is not a leaf node Root Parent of Parent of Child of Root Father of Child of Leaf Child of The root does not have a parent A leaf does not have children
  • 20. Balanced and unbalanced trees ī‚¤ The leaves could be positioned at different levels; their positioning defines the tree balancing property ī‚¤ If leaves are position “closely” (e.g., at maximum a single level separates them) then the tree is balanced Tree (perfectly) balanced Unbalanced tree
  • 21. Definitions ī‚¤ Node height: length of the longest path between the node and a leaf ī‚¤ Node depth: length of path from the node and the tree root Height Depth
  • 22. Definitions ī‚¤ Sub-tree of a tree T: tree consisting in a node n belonging to tree T, together with all its descendants in T ī‚¤ The sub-tree corresponding to the root T is the whole tree T
  • 24. Binary tree vs. N-ary tree ī‚¤ A binary tree is a tree whose nodes can have two children at maximum ī‚¤ An n-ary tree is a tree where there does not exist a limit on the number of children a node could have
  • 25. Binary complete trees vs. Binary incomplete trees ī‚¤ A tree is complete if it is a binary tree and: ī‚¤ Each level (except the last) is full of nodes ī‚¤ The nodes are at the leftmost positions ī‚¤ The last level may contain few nodes, but it has to be filled from left to right Complete tree Incomplete tree
  • 26. Binary tree: from concept to implementation ī‚¤ We are going to store the tree as a dynamic data structure ī‚¤ Ideas?
  • 27. Binary tree: from concept to implementation ī‚¤ We are going to store the tree as a dynamic data structure ī‚¤ How to position them? Ingredients What to represent Struct Pointers Nodes Edges
  • 28. Binary tree: from concept to implementation Ingredients What to represent Struct Pointers Nodes Edges ī‚¤ We are going to store the tree as a dynamic data structure ī‚¤ We’ll use the same principles used with linked lists:
  • 29. Binary tree: Structure ī‚¤ Each node in a binary tree contains: ī‚¤ A left pointer ī‚¤ A right pointer ī‚¤ Data ī‚¤ The pointers in the node point recursively at two sub-trees (i.e., smaller trees) positioned on its left side and right side Left Sub-tree Right Sub-tree Left Sub-tree Right Sub-Tree
  • 30. Binary tree: Structure ī‚¤ We’ll see then a node as follows: ī‚¤ Note. Since the node structure is dynamic, we have to be very careful in handling the pointer to the root: if we lose it, we lose every possibility of accessing to the tree! Data contained in the node Left sub-tree Right sub-tree
  • 32. Binary tree: Structure 2 7 8 2 9 3 1 The root is pointed to by a “head” pointer
  • 33. Binary tree: Structure 2 7 8 2 9 3 1 Leaves have left and right pointers set to null
  • 34. Incomplete binary tree ī‚¤ Internal nodes do not have necessarily both left and right children, some of them may be null 2 7 8 9 3 2 7 8 3 1
  • 35. Manual creation of a binary tree
  • 36. Binary tree: manual creation 1 rootNode 2 3 leftChild rightChild 4 leftChild2 5 rightChild2 rightChild2->data = 5; rightChild2->leftPtr = NULL; rightChild2->rightPtr = NULL;
  • 37. Binary tree: manual creation 1 rootNode 2 3 leftChild rightChild 4 leftChild2 5 rightChild2 rootNode->leftPtr = leftChild; rootNode->rightPtr = rightChild;
  • 38. Binary tree: manual creation 1 rootNode 2 3 leftChild rightChild 4 leftChild2 5 rightChild2 leftChild->leftPtr = leftChild2; leftChild->rightPtr = rightChild2;
  • 40. Counting nodes ī‚¤ Aim: counting the number of nodes in the tree ī‚¤ The approach we propose for any algorithm involving tree manipulation is recursive. Thus, it is necessary to define: ī‚¤ A base case ī‚¤ A recursion step ī‚¤ Hint: always look for base case in the leaves of the treeâ€Ļ
  • 41. Counting nodes 1+ nodes-left + nodes-right 1+ nodes-left + nodes-right 1+ nodes-left + nodes-right To visit the child nodes of n, we visit first its left sub-tree and then its right sub-tree Given a node n, we count the number of nodes in the sub-tree having n as root as: 1 + “the number of child nodes on the left” + “the number of child nodes on the right”
  • 42. Counting nodes 1+ nodes-left + nodes-right 1+ nodes-left + nodes-right 1+ nodes-left + nodes-right = 0 = 0 1+ nodes-left + nodes-right 1+ 1 + nodes-right When we reach a leaf, we go back to its parent node īƒŧ If we were visiting the left sub-tree, we move to the right sub-tree
  • 43. Counting nodes 1+ nodes-left + nodes-right 1+ 1 + nodes-right 1+ nodes-left + nodes-right = 0 1+ nodes-left + nodes-right 1+ 1 + nodes-right 1+ 0 + nodes-right = 0 1+ nodes-left + nodes-right = 0
  • 44. Counting nodes 1+ nodes-left + nodes-right 1+ 1 + nodes-right 1+ 0 + 1 1+ nodes-left + nodes-right 1+ 1 + 2
  • 45. Counting nodes 1+ 4 + nodes-right 1+ 4 + nodes-right 1+ nodes-left + nodes-right 1+ 4 + nodes-right 1+ 0+ nodes-right 1+ nodes-left + nodes-right = 0 = 0 = 0
  • 46. Counting nodes 1+ 4 + nodes-right 1+ 0 + 1 1+ 4 + 2 Node count = 7
  • 47. Counting nodes ī‚¤ The proposed procedure is, again, recursive ī‚¤ When we reach a node (any node): ī‚¤ We add +1 to count the current node ī‚¤ We ask to count nodes in the left sub-tree ī‚¤ We ask to count nodes in the right sub-tree ī‚¤ The base case is on a null pointer (i.e., a “missing” left sub-tree or right sub-tree). It is NOT a node: ī‚¤ It does not have left children ī‚¤ It does not have right children ī‚¤ Its contribution to the total count is 0
  • 48. Counting nodes ī‚¤ Question: while performing the recursive calls, do the pointers to the nodes have to be passed by copy or by reference?
  • 49. Counting nodes ī‚¤ Question: while performing the recursive calls, do the pointers to the nodes have to be passed by copy or by reference? Do I have to propagate any updates to the pointer when I return from the recursive call execution?
  • 50. Counting nodes ī‚¤ Question: while performing the recursive calls, do the pointers to the nodes have to be passed by copy or by reference? Do I have to propagate any updates to the pointer when I return from the recursive call execution? Do I need to change the tree structure?
  • 51. Counting nodes ī‚¤ Answer: counting nodes does not have to change the tree structure ī‚¤ If I passed any pointer by reference, and it was modified by the function, it would update the pointer in the caller, changing the structure of the tree (“where is the root of the tree now?”)
  • 52. Counting nodes Pointer to the current node Base case Recursive step
  • 54. Computing tree height ī‚¤ Tree height: length of the longest path between the root and a leaf Height
  • 55. Computing tree height ī‚¤ The common trick to write correctly tree manipulation functions is to understand which are the base case and the recursion step ī‚¤ The base case is usually set on the leaves of the tree ī‚¤ Which is the right approach to compute tree height?
  • 56. Computing tree height ī‚¤ The common trick to write correctly tree manipulation functions is to understand which are the base case and the recursion step ī‚¤ The base case is usually set on the leaves of the tree ī‚¤ Which is the right approach to compute tree height? ī‚¤ Base case: if the current pointer is NULL, it means we are at the “end” (lower end) of the tree. Thus, the current height is 0 (we are at the base of the tree) Height
  • 57. Computing tree height ī‚¤ The common trick to write correctly tree manipulation functions is to understand which are the base case and the recursion step ī‚¤ The base case is usually set on the leaves of the tree ī‚¤ Which is the right approach to compute tree height? ī‚¤ Base case: if the current pointer is NULL, it means we are at the “end” (lower end) of the tree. Thus, the current height is 0 (we are at the base of the tree) ī‚¤ Generic case: if the current pointer is NULL, the current node’s height is 1 + the height of its chidren Height
  • 58. Computing tree height Base Height with respect to the base: 0 Height (with respect to the base): 1 Height (with respect to the base): 2 Height (with respect to the base): 3
  • 59. Computing tree height My child’s height: 0 My height: 1+0 = 1 My child’s height: 1 My height: 1+1 = 2 My left child’s height: 1 My right child’s height: 2 My height: 1+max(1,2) = 3 Base Height with respect to the base: 0 Height (with respect to the base): 1 Height (with respect to the base): 2 Height (with respect to the base): 3
  • 60. Computing tree height Height of sub-tree having root leftPtr Height of sub-tree having root rightPtr
  • 61. Element search in the tree
  • 62. Element search in the tree ī‚¤ Element search returns: ī‚¤ NULL if the element is not in the tree ī‚¤ A pointer to the node that contains the element, if the element is in the tree ī‚¤ The tree is not ordered. Thus, given a node, the element that we are looking for could be: ī‚¤ The current node ī‚¤ A node in the left sub-tree ī‚¤ A node in the right sub-tree ī‚¤ â€Ļnot present, too!
  • 63. Element search in the tree ī‚¤ We will return currentNode ifâ€Ļ?
  • 64. Element search in the tree ī‚¤ We will return currentNode if: ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we did not find anything along the path we followed) ī‚¤ currentNode contains the element (i.e., the search is done)
  • 65. Element search in the tree ī‚¤ We will return currentNode if: ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we did not find anything along the path we followed) ī‚¤ currentNode contains the element (i.e., the search is done) ī‚¤ In case currentNode is not NULL and not containing the element we want to findâ€Ļ?
  • 66. Element search in the tree ī‚¤ We will return currentNode if: ī‚¤ currentNode is NULL (i.e., we got to the end of the tree and we did not find anything along the path we followed) ī‚¤ currentNode contains the element (i.e., the search is done) ī‚¤ In case currentNode is not NULL and not containing the element we want to find: ī‚¤ We look for the element in the left sub-tree. If the element is here, I’ll return it ī‚¤ If the element is NOT in the left sub-tree, I’ll return the result of the search in the right sub-tree ī‚¤ Either the element, if present, or NULL
  • 67. Element search in the tree
  • 68. Element search in the tree Equivalentlyâ€Ļ
  • 69. Printing tree nodes AKA: how to merge linked lists and binary trees
  • 70. Printing tree nodes ī‚¤ Paths in the tree may have different lengths ī‚¤ Approach: ī‚¤ navigate the tree first at the left side, then at the right side ī‚¤ store each path in a linked list ī‚¤ when we reach a leaf, the path is as its end, thus we can print it (i.e., we print the content of the linked list) 1 2 3 4 5
  • 71. Printing tree nodes 1 2 4 1 2 5 1 3 1 2 3 4 5
  • 72. Printing tree nodes ī‚¤ How do we print paths? ī‚¤ That is: ī‚¤ How do we navigate through the tree so as to visit every path, one after another? ī‚¤ How to store a path in a linked list?
  • 73. Printing tree nodes ī‚¤ How do we navigate through the tree so as to visit every path, one after another? ī‚¤ We visit the tree by traversing the left sub-trees first and the right sub-trees after ī‚¤ This is similar to what happened with the nodes printing procedure ī‚¤ How to store a path in a linked list? ī‚¤ At first, we initialize the list as an empty list ī‚¤ As we visit nodes along a path, we attach those nodes in the list ī‚¤ On the head? On the tail?
  • 74. Printing tree nodes ī‚¤ How do we navigate through the tree so as to visit every path, one after another? ī‚¤ We visit the tree by traversing the left sub-trees first and the right sub- trees after ī‚¤ This is similar to what happened with the nodes printing procedure ī‚¤ How to store a path in a linked list? ī‚¤ At first, we initialize the list as an empty list ī‚¤ As we visit nodes along a path, we attach those nodes in the list ī‚¤ On the tail, otherwise we will print the path in the wrong direction!
  • 75. Printing tree nodes: initializing the linked list ī‚¤ In printPaths(): ī‚¤ We initialize the list head ī‚¤ We initialize the list tail ī‚¤ We start the tree printing procedure 1 2 3 4 5 rootNode pathHead pathTail overload
  • 76. Printing tree nodes 1 2 3 4 5 rootNode At first we print this pathâ€Ļ 1 2 3 4 5 rootNode â€Ļthen this one. 1 2 3 4 5 rootNode We go to the left sub-treeâ€Ļ 1 2 3 4 5 rootNode â€Ļand again to the left sub-tree. We are at a leaf: we print the list
  • 77. Printing tree nodes 1 2 3 4 5 rootNode 1 2 3 4 5 rootNode 1 2 3 4 5 rootNode To print this path we go back to the rootâ€Ļ 1 2 3 4 5 rootNode â€Ļand we go to the right child. We are at a leaf: we can print the list. We go back to the parentâ€Ļ â€Ļand then to the right child. We are at a leaf: we print the list
  • 78. Printing tree nodes ī‚¤ We insert the root in the list: 1 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 4 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 2 5 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We remove the left child from the list: 1 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 3 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 ī‚¤ We remove the root from the list: 1 2 3 4 5
  • 79. ī‚¤ We insert the root in the list: 1 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 4 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 2 5 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We remove the left child from the list: 1 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 3 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 ī‚¤ We remove the root from the list: Printing tree nodes First level 1 2 3 4 5
  • 80. ī‚¤ We insert the root in the list: 1 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 4 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 2 5 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We remove the left child from the list: 1 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 3 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 ī‚¤ We remove the root from the list: Printing tree nodes Second level 1 2 3 4 5
  • 81. ī‚¤ We insert the root in the list: 1 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 ī‚¤ We require to print the left child ī‚¤ We insert the left child in the list: 1 2 4 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 2 5 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 2 ī‚¤ We remove the left child from the list: 1 ī‚¤ We require to print the right child ī‚¤ We insert the right child in the list: 1 3 ī‚¤ We are at a leaf: we print the list ī‚¤ We remove the leaf node from the list: 1 ī‚¤ We remove the root from the list: Printing tree nodes Base case: leaf node 1 2 3 4 5
  • 82. Printing tree nodes ī‚¤ The procedure is recursive ī‚¤ When we reach a node ī‚¤ We add its content to the list ī‚¤ We ask to print the left tree ī‚¤ We ask to print the right tree ī‚¤ We remove its content from the list ī‚¤ Base case: on the leaf ī‚¤ We insert its content in the list ī‚¤ We ask to print the path from the root to that leaf ī‚¤ We remove its content from the list
  • 84. Printing tree nodes First case: empty list I have to add the root to the list īƒŧ pathHead = NULL īƒŧ pathTail = NULL newNode
  • 85. Printing tree nodes newNode pathHead pathTail First case: empty list I have to add the root to the list īƒŧ pathHead = NULL īƒŧ pathTail = NULL
  • 86. Printing tree nodes Second case: non-empty list We add either a leaf node or an internal node to the list newNode pathHead pathTail
  • 87. Printing tree nodes newNode pathHead pathTail Second case: non-empty list We add either a leaf node or an internal node to the list
  • 90. Printing tree nodes Generic case: either internal nodes or root node
  • 93. Graph ī‚¤ A graph is a set of nodes connected via edges ī‚¤ It is usually represented as G(V,E), where: ī‚¤ V is the set of nodes ī‚¤ E is the set of edges ī‚¤ Trees vs. graphs ī‚¤ A tree has a unique root, while the graph could have multiple roots ī‚¤ Tree nodes have just an incoming edge, while graph edges could have multiple incoming edges
  • 94. N-ary trees ī‚¤ Generalization of binary trees ī‚¤ Every node could have an arbitrary number of children ī‚¤ It is generally used to represent hierarchical structures (e.g., company employees hierarchy)
  • 96. Counting leaf and non-leaf nodes ī‚¤ Write: ī‚¤ A function that counts the number of leaf nodes ī‚¤ A function that counts the number of non-leaf nodes
  • 97. Counting leaf and non-leaf nodes ī‚¤ A leaf node is a node without children ī‚¤ leftPtr is NULL ī‚¤ rightPtr is NULL ī‚¤ The non-leaf nodes (called internal nodes) areâ€Ļ all the other nodes! non_leaf_nodes = total_nodes – leaf_nodes
  • 98. Counting leaf and non-leaf nodes
  • 99. Counting nodes on even levels ī‚¤ Write a function that counts the number of nodes on even levels of the tree ī‚¤ Even levels are the ones having even ID Level 1 Level 2 Level 3 Level 4
  • 100. Counting nodes on even levels ī‚¤ We keep track of the current depth with an integer ī‚¤ depth = 1 is we are on the root ī‚¤ depth = 2 if we are on the root’s children ī‚¤ â€Ļ ī‚¤ If dividing depth by 2 has null reminder, then we add 1 to the count of nodes on even levels
  • 101. Counting nodes on even levels
  • 102. Equal trees ī‚¤ Write a function that, given two trees, returns ī‚¤ true if the trees are identical ī‚¤ false if the trees are not identical
  • 103. Equal trees ī‚¤ Given a node n and a node m, the sub-trees having n and m as root are identical if: ī‚¤ n and m contain the same value ī‚¤ The sub-trees having n->leftPtr and m->leftPtr as root are identical ī‚¤ The sub-trees having n->rightPtr and m->rightPtr as root are identical
  • 105. Tree depth ī‚¤ Write a function that checks whether all the paths have equal length
  • 107. Sum of leaf nodes (1) ī‚¤ Write a function that provides the sum of leaf nodes
  • 108. Sum of leaf nodes (1)
  • 109. Sum of leaf nodes (2) ī‚¤ Assume that every path is associated with a score, which can be computed by summing the node values along that path. Thus, if the tree contains N paths, it contains N scores too (one for each path) ī‚¤ Write a function that returns the highest score
  • 110. Sum of leaf nodes (2)
  • 111. Sum of leaf nodes(2) (alternative solution)
  • 112. Serialize leaves ī‚¤ Write a function that extracts all the leaves from the tree and builds a linked list, in which each node represents one of the leaves of the tree
  • 113. Serialize leaves We go down at the left We go back and go down at the right We go back and go down at the right
  • 115. Ordered tree insertion ī‚¤ Write a function that, given a vector<string> as an input,inserts the words in a tree in an ordered manner: for every node n in the tree, every word in the left sub-tree come before the word in n alphabetically, while all the others are in the right sub-tree Vector: dog, cat, horse, alpaca, bee, shark, fox, mosquito, sheep
  • 116. Ordered tree insertion ī‚¤ For each word from the vector: ī‚¤ If it precedes the word contained in the current node, it has to go down in the left sub-tree ī‚¤ If it follows the word contained in the current node, it has to go down in the right sub-tree cat < dog horse > dog alpaca < dog alpaca < cat
  • 117. Ordered tree insertion For each elementâ€Ļ â€Ļwe verify its position and insert it as a leaf
  • 120. Even or odd levels? ī‚¤ Write a function that returns true if every number contained in the even levels are even and every number in the odd levels are odd, or false otherwise
  • 121. Even or odd levels?
  • 122. Equal sum on trees ī‚¤ Write a function that, given two binary trees, returns true if: ī‚¤ The sum of the leaves of the two trees is equal ī‚¤ OR ī‚¤ The first tree has at least a leaf whose value is equal to the sum of the values in the leaves of the second tree ī‚¤ or false otherwise
  • 123. Equal sum on trees
  • 124. Equal sum on trees
  • 125. Equal sum on trees
  • 126. The mirror ī‚¤ Change a tree in its mirrored version
  • 127. The mirror ī‚¤ Mirroring the tree means that: ī‚¤ What is on the left has to go on the right ī‚¤ What is on the right has to go on the left ī‚¤ We are building a new tree, thus every time we return the pointer to the new node ī‚¤ Behavior: ī‚¤ What to do when the pointer is NULL? ī‚¤ What to do on the nodes?
  • 128. The mirror ī‚¤ Mirroring the tree means that: ī‚¤ What is on the left has to go on the right ī‚¤ What is on the right has to go on the left ī‚¤ We are building a new tree, thus every time we return the pointer to the new node ī‚¤ Behavior: ī‚¤ When the pointer is NULL: we return NULL (nothing has to be created) ī‚¤ On the nodes: we return the current node and its sub-trees, which are swapped
  • 131. References ī‚¤ Alberi: http://it.wikipedia.org/wiki/Albero_(informatica) ī‚¤ http://www.di.unisa.it/~demarco/sd/lezioni/lezione11.pdf