Loading in 2 Seconds...
Loading in 2 Seconds...
Computer Science 2 Data Structures and Algorithms V22.0102 section 2 Introduction to Trees Professor: Evan Korth New York University. Road Map. Introduction to trees Terminology Binary trees Tree traversal Reading: 4.1 – 4.2. Tree. Tree defined recursively
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.
Computer Science 2Data Structures and AlgorithmsV22.0102 section 2 Introduction to Trees
Professor: Evan KorthNew York University
Source:Mark Allen Weiss
Source:Mark Allen Weiss  edited by Evan Korth
Source:Mark Allen Weiss
Source:Mark Allen Weiss
To traverse (or walk) the binary tree is to visit each node in the binary tree exactly once
Tree traversals are naturally recursive
Since a binary tree has three “parts,” there are six possible ways to traverse the binary tree:
root, left, right
left, root, right
left, right, root
root, right, left
right, root, left
right, left, root
Tree traversalsSource: David Matuszek
Source: David Matuszek
Source: David Matuszek
Source: David Matuszek
To traverse the tree, collect the flags:
preorder
inorder
postorder
A
A
A
B
C
B
C
B
C
D
E
F
G
D
E
F
G
D
E
F
G
A B D E C F G
D B E A F C G
D E B F G C A
Tree traversals using “flags”Source: David Matuszek
Source: David Matuszek
2

3
2
5
1
Arithmetic Expression Tree((2 (5  1)) + (3 2))
2

3
2
5
1
Print Arithmetic Expressionsvoid printTree(t)
//binary operands only
if (t.left != null) print("(");
printTree (t.left);
print(t.element );
if (t.right != null)
printTree (t.right);
print (")");
((2 (5  1)) + (3 2))
2

3
2
5
1
Evaluate Arithmetic Expressionsint evaluate (t)
//binary operators only
if (t.left == null) //external node return t.element;
else //internal node
x = evaluate (t.left);
y = evaluate (t.right);
let o be the operator t.element
z = apply o to x and y
return z;