0% found this document useful (0 votes)
35 views30 pages

L11 Trees and Traversals

Binary trees

Uploaded by

Jessica Milner
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)
35 views30 pages

L11 Trees and Traversals

Binary trees

Uploaded by

Jessica Milner
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/ 30

Trees and Traversal

Start Thinking Nonlinearly


What is a Tree
In computer science, a tree is an
abstract model of a hierarchical
structure

A tree consists of nodes with a


parent-child relation

Applications:

● Organization charts
● File systems
● Programming environments
What is a Tree
A tree can also be looked at as
having vertices and edges without
having any cycles.

The tree with no nodes is called the


null or empty tree.

A tree that is not empty consists of a


root node and potentially many
levels of additional nodes that form a
hierarchy.
What is a Tree
Trees are portrayed with the
root at the top and the other
nodes growing downward.
a e f c f
This does not need to be the
case, but is easier to read b c d g b

These are the same two f g f


a
trees, but one is definitely
more readable e d

Arrows can help direct the


eye, but are optional
Tree Terminology
a a a

b c d b c d b c d

f g f f g f f g f

e e e

a is the root node g is a child of b d is the parent of f


(top most node) (directly connected (directly connected
below) above)
Tree Terminology
a a a

b c d b c d b c d

f g f f g f f g f

e e e

b, c, and d are e is a descendant of a is a ancestor of e


siblings b (repeatedly moving
(same parent) (repeatedly moving from child to parent)
from parent to child)
Tree Terminology
a a a

b c d b c d b c d

f g f f g f f g f

e e e

c is a leaf (or d is a branch (or Path from a to g


external node) internal node) (connection
(has no children) (has children) between nodes)
Tree Terminology
a a a

b c d b c d b c d

f g f f g f f g f

e e e

f has a depth of 2 The tree has a height of b and it’s


(edges between root 3 descendents are a
and node) (edges on the longest subtree of a
path from root to a leaf)
Tree ADT
We use positions to abstract nodes Position-based methods:

Generic methods: ● position p.parent()


● list<position> p.children()
● integer size()
● boolean empty() Query methods:

Accessor methods: ● boolean p.isRoot()


● boolean p.isExternal()
● position root()
● list<position> positions() Additional update methods may be defined by
data structures implementing the Tree ADT
Tree ADT
● An abstract tree (or abstract hierarchy) does not restrict the number of nodes

○ In this tree, the degrees vary:


Tree ADT: Design
We implement an abstract tree or hierarchy by using a class that:

○ Stores a value

○ Stores the children in a linked-list


Implementation
● The tree with six nodes would be stored as follows
template <typename E> // base element type
class Position<E> { // a node position
public:
E& operator*(); // get element
Position parent() const; // get parent
PositionList children() const; // get node's children
bool isRoot() const; // root node?
bool isExternal() const; // external node?

Interface*
};

template <typename E> // base element type


class Tree<E> {
Public: // public types
Trees class Position; // a node position
class PositionList; // a list of positions

int size() const; // number of nodes


bool empty() const; // is tree empty?
Position root() const; // get the root
PositionList positions() const; // get positions of all nodes
};

*Note: These are simplifications of the actual implementations/interfaces for trees.


The concrete particulars are not as important when learning how to traverse the data
structures. When we cover binary trees, we will go more into the specifics..
Tree ADT
Depth and int depth(const Tree& T, const Position& p) {

Height
if (p.isRoot()) {
return 0; // root has depth 0
} else {
return 1 + depth(T, p.parent()); // 1 + (depth of parent)
}
Trees }

The running time of algorithm depth(T,p) is 𝑂(𝑑𝑝 )


int height1(const Tree& T) {
int h = 0;
PositionList nodes = T.positions(); // list of all nodes

Depth and
for (Iterator q = nodes.begin(); q != nodes.end(); ++q) {
if (q->isExternal()) {
h = max(h, depth(T, *q)); // get max depth among leaves

Height
}
}
return h;
}
int height2(const Tree& T, const Position& p) {
Trees if (p.isExternal()) return 0; //leaf has height 0
int h=0;
PositionList ch = p.children(); //list of children
The runtime of algorithm height1 is 𝑂(𝑛 + for (Iterator q = ch.begin(); q != ch.end(); ++q) {
σ𝑝(1 + 𝑑𝑝 )) h = max(h, height2(T, *q)
The runtime of algorithm height2 is return 1+h; // 1+max height of children
𝑂( σ𝑝(1 + 𝑐𝑝 )), where 𝑐𝑝 is the number of
children of a node p
Preorder
A traversal visits the
nodes of a tree in a
systematic manner

In a preorder traversal,
a node is visited before
its descendants
1. Make Money Fast! 6. 2.1 Stock Fraud
2. 1. Motivations 7. 2.2 Ponzi Scheme
Application: print a 3. 1.1 Greed 8. 2.3 Bank Robbery
4. 1.2 Avidity 9. References
structured document 5. 2. Methods
Preorder
A traversal visits the
nodes of a tree in a
systematic manner

In a preorder traversal,
a node is visited before
its descendants 1. Paper 8. §2.1
2. Title 9. §2.2
3. Abstract 10. §2.3
Application: print a 4. §1 11. §3
5. §1.1 12. §3.1
structured document 6. §1.2 13. §3.2
7. §2 14. References
void preorderPrint(const Tree& T, const Position& p) {

Preorder Print
cout << *p; // print element
PositionList ch = p.children(); // list of children
for (Iterator q = ch.begin(); q != ch.end(); ++q) {
cout << " ";
preorderPrint(T, *q);
Trees }
}
Postorder
In a postorder
traversal, a node is
visited after its
descendants

Application: compute
space used by files in a
1. h1c.doc 5. Stocks.cpp
directory and its 2. h1nc.doc 6. Robot.cpp
3. homeworks/ 7. programs/
subdirectories 4. DDR.cpp 8. todo.txt
9. cs16/
Postorder
In a postorder
traversal, a node is
visited after its
descendants

Application: compute
space used by files in a 1. Title 8. §2.3
2. Abstract 9. §2
directory and its 3. §1.1 10. §3.1
4. §1.2 11. §3.2
subdirectories 5. §1 12. §3
6. §2.1 13. References
7. §2.2 14. Paper
void postorderPrint(const Tree& T, const Position& p) {

Postorder Print
PositionList ch = p.children(); // list of children
for (Iterator q = ch.begin(); q != ch.end(); ++q) {
postorderPrint(T, *q);
cout << " ";
}
Trees cout << *p; // print element
}
Preorder and Postorder
Algorithm preOrder(v) { Algorithm postOrder(v) {
visit(v) for each child w of v {
for each child w of v { postOrder (w)
preOrder(w) }
} visit(v)
} }
Project 2
● The three notations are:
○ Postfix (Reverse Polish) Notation:

■ Operators are written after operands A B - C + == (A - B) + C

○ Infix Notation:

■ The standard notation we use where the operator is between the operands.

○ Prefix (Polish) Notation:

■ Operators are written before operands: * - A B C == (A - B) * C

● How you represent expressions 𝐴 + 𝐵 ∗ 𝐶 𝑎𝑛𝑑 (𝐴 + 𝐵) ∗ 𝐶 in the postfix and prefix


Notations?
24
Project 2
● How you represent expressions 𝐴 + 𝐵 ∗ 𝐶 𝑎𝑛𝑑 (𝐴 + 𝐵) ∗ 𝐶 in the postfix and prefix
Notations?

Infix A+B*C (A+B)*C

Postfix ABC*+ AB+C*

Prefix +A*BC *+ABC

25
Question:
Let T be a tree with void parenPrint(const Tree& T, const Position& p) {
cout << *p; // print node's element

n nodes. What is the if (!p.isExternal()) {


PositionList ch = p.children(); // list of children

running time of the


cout << "( "; // open
for (Iterator q = ch.begin(); q != ch.end(); ++q) {
if (q != ch.begin()) cout << " "; // print separator

function? }
parenPrint(T, *q); // visit the next child

cout << " )"; // close

parenPrint(T, }
}

T.root())
Question:
Which of these are valid trees? If not,
why?
A B C D E F
Question:
There are three boxes:
a box containing two gold coins,
a box containing two silver coins,
a box containing one gold coin and a silver coin.

After choosing a box at random and pulling one coin, you pull a gold
coin. What is the probability that the box you chose has the two gold
coins.

Using a tree, prove your answer.


Question
Let T be the tree given below
Question
Give the output of preorderPrint(T, T.root())

Give the output of postorderPrint(T, T.root())

What is the depth of node “Canada” in T

What is the height of the tree T

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy