binary trees Flashcards
Initiating
class TreeNode<E> {
E element;
TreeNode<E> left;
TreeNode<E> right;
public TreeNode(E o) {
element = o;
}
}</E></E></E>
Search method
public boolean search(E element) {
TreeNode<E> current = root; //Start from root
while (current != null)
if (element < current.element) {
current = current.left; // Go left
}
else if (element > current.element) {
current = current.right; // Go right
}
else // Element matches current.element
return true; // Element is found
return false; // Element is not in the tree
}</E>
Insert method
if (root == null)
root = new TreeNode(element);
else {
// Locate the parent node
current = root;
while (current != null)
if (element value < the value in current.element) {
parent = current;
current = current.left;
}
else if (element value > the value in current.element) {
parent = current;
current = current.right;
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent.element)
parent.left = new TreeNode(element);
else
parent.right = new TreeNode(element);
return true; // Element inserted
}
Inorder
The inorder traversal is to visit the left subtree of the
current node first recursively, then the current node itself,
and finally the right subtree of the current node recursively.
Postorder
The postorder traversal is to visit the left subtree of the
current node first, then the right subtree of the current
node, and finally the current node itself.
Preorder
The preorder traversal is to visit the current node first,
then the left subtree of the current node recursively, and
finally the right subtree of the current node recursively
Breadth-first
The breadth-first traversal is to visit the nodes level by
level. First visit the root, then all children of the root from
left to right, then grandchildren of the root from left to
right, and so on.