Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
PCS4
PCS 4: Overview
Week Subject Book
1 Delegates & Events Nothing
2 RFID Reader & Sorting (Selection sort) § 18.3.1
3 Recursion & Binary search § 7.15 & §18.2
4 Passing arguments by: value/reference § 7.16
“ref” & “out” parameters
5 Linked lists, stacks, queues § 19.4
6 Binary trees § 19.7
7 Repetition (Mock exam)
9 Exam
Binary Tree
3
Binary Tree: What is it?
• A binary tree is a rooted a
(directed) tree
b c
• “b” is the left child of “a”
• “c” is the right child of “a”
d e f
• “a” is parent of “b” and “c”
g h
Binary Tree: Sub-trees
• The blue indicated part is the left subtree a
d e f
g h
Binary Tree: How does it work?
• How could we program a node in C#?
• How can we represent the children?
• What kind of operations would you want to perform on a node?
a
b c
d e f
Binary Tree: Node Code
class TreeNode a
{
public int Value{ get; set; } b c
public TreeNode LeftTree { get; set; }
public TreeNode RightTree { get; set; } d e f
public TreeNode(int value)
{ g h
Value = value;
LeftTree = RightTree = null;
}
}
7
Binary Tree: Tree Code (part 1)
class BinaryTree a
{
private TreeNode Root { get; set; } b c
public BinaryTree()
{ d e f
Root = null;
} g h
}
8
Binary Tree: Tree Code (part 2)
• How to insert a new Node? a
d e f
g h
9
Binary Tree: Insert
• Let us try! a
b c
d e f
g h
10
Binary Tree: Traversal
• If we want to display a Binary tree in a GUI we could do this by:
• Preorder
a
• Inorder
• Postorder
b c
d e f
g h
Binary Tree: Preorder
a
Preorder:
1. Start with the
root b c
2. Order the left
subtree in d e f
preorder
3. Order the g h
right subtree
in preorder
Binary Tree: Preorder (result)
• a,b,d,g,h,c,e,f a
b c
d e f
g h
Binary Tree: Inorder (result)
Inorder: a
1. Order the left
subtree in b c
inorder
2. Process the d e f
root
3. Order the right
g h
subtree in
inorder
Binary Tree: Inorder (result)
• g,d,h,b,a,e,c,f a
b c
d e f
g h
Binary Tree: Postorder
a
Postorder:
1. Order the left
subtree in b c
postorder
2. Order the d e f
right subtree
in postorder g h
3. Process the
root
Binary Tree: Postorder (result)
• g,h,d,b,e,f,c,a a
b c
d e f
g h