Binary Trees What if a node has more one field that refers to another n

Binary Trees What if a node has more one field that refers to another node? Not to form a doubly-­‐
linked lists, but to branch. Trees are extremely powerful and elegant. They are useful for solving many problems and are one of the most commonly used data structures. Eg, • Decision trees, • ancestral trees • game trees • organizational charts • arithmetic expression trees • folders/directories on a computer. Terminology: Trees with 1, 2 , 3 nodes *
*
*
/
\
*
*
*
/ \
*
*
*
/
*
*
/
*
*
/
*
\
*
\
*
\
/
*
*
*
\
*
How many different shaped trees are there 5 nodes? A lot! Therefore, you need a way to think about trees at a "high level" and not consider every possible shape tree. Implementing a binary tree: binary tree node (inner class) private static class BTNode<E> {
private E data;
private BTNode<E> left;
private BTNode<E> right;
public BTNode(E element) {
data = element;
left = null;
right = null;
}
}
Recursive data types: Linked List is either • empty linked list (null) or (base case) • a node followed by a linked list (recursive case) With linked lists we can write code either iteratively or recursively. Recursive solutions are often more elegant. public int size (Node<E> list) {
int count = 0;
while (node != null) {
count++;
node = node.next;
}
return count;
}
public int size (Node<E> list) {
if (node == null) return 0;
else {
return 1 + size(node.next);
}
}
Binary Tree is either • empty tree (null) or (base case) • a root node with left and right subtrees (recursive case) Key point: A subtree is a smaller that the whole tree, which is leads towards the base case in the recursive definition. With trees, we almost always write recursive methods. public int size (BTNode<E> node) { if (node == null) {
return 0;
}
else {
return size(node.left) +
size(node.right) + 1;
}
}
The maximum of the whole tree is the maximum of the following three values: the root, the maximum of the left subtree, and the maximum of the right subtree. // Precondition: node is not null
public int max(BTNode<Integer> node) {
int max = t.data;
if (node.left != null) {
int left = max(t.left);
if (left > max)
max = left;
}
if (node.right != null) {
int right = max(t.left);
if (right > max)
max = right;
}
return max;
}
Several students wanted to start with the maximum being the minimum integer in Java, so that the code could be written in the same styles as the size method. But suppose we were looking for the "smallest" string (the string that occurs first lexicographically). Correspondingly, what would be the "largest" string? It is much better to start with one of the elements in the tree for finding the maximum or minimum.