nodes
Trees
: binary, balanced, ordered, etc.Graphs
: directed / undirected, weighted, etc.Networks
Tree
data structure – terminology
Binary trees
: the most widespread form
Binary search trees
are ordered
x
in the tree
x
are ≤ x
x
are > x
balanced
Balanced trees
have height of ~ log(x)
log(n)
stepstree
data structure:
public class TreeNode<T>
{
private T value;
private List<TreeNode<T>> children;
…
}
The value contained in the node
List of child nodes, which are of the same type
public TreeNode(T value)
{
this.value = value;
this.children = new List<TreeNode<T>>();
}
public T Value
{
get { return this.value; }
set { this.value = value; }
}
public void AddChild(TreeNode<T> child)
{
child.hasParent = true;
this.children.Add(child);
}
public TreeNode<T> GetChild(int index)
{
return this.children[index];
}
Tree<T>
keeps tree’s root nodepublic class Tree<T>
{
private TreeNode<T> root;
public Tree(T value, params Tree<T>[] children) : this(value)
{
foreach (Tree<T> child in children)
{
this.root.AddChild(child.root);
}
}
public TreeNode<T> Root
{
get { return this.root; }
}
}
Flexible constructor for building trees
Tree<int> tree =
new Tree<int>(7,
new Tree<int>(19,
new Tree<int>(1),
new Tree<int>(12),
new Tree<int>(31)),
new Tree<int>(21),
new Tree<int>(14,
new Tree<int>(23),
new Tree<int>(6))
);
Traversing a tree
means to visit each of its nodes exactly one in particular order
Depth-First Search
(DFS)
Breadth-First Search
(BFS)
Depth-First Search
first visits all descendants of given node recursively, finally visits the node itselfDFS(node)
{
for each child c of node
DFS(c);
print the current node;
}
Breadth-First Search
first visits the neighbor nodes, later their neighbors, etc.BFS(node)
{
queue node
while queue not empty
v queue
print v
for each child c of v
queue c
}
BFS(node)
{
queue node
while queue not empty
v queue
print v
for each child c of v
queue c
}
DFS(node)
{
stack node
while stack not empty
v stack
print v
for each child c of v
stack c
}
Binary Search Trees
)
x
the left subtree has values ≤ x
and the right subtree has values > x
log2(n)
where n
is the number of their nodeslog2(n)
comparisonsAVL trees
– ideally balanced, very complexRed-black trees
– roughly balanced, more simpleAA-Trees
– relatively simple to implementlog(n)
stepsB-trees
are generalization of the concept of ordered binary search trees
d
has between d
and 2xd
keys in a node and between d+1
and 2xd+1
child nodesSortedDictionary<K,V>
OrderedSet<T>
Wintellect Power Collections for .NET
" are more flexible