ch 4 trees Flashcards
depth
path from the root to n (root is at 0)
height
leaf n to root (leaf is at 0)
class Binarynode (what are the instance variables)
object element (the data in the node) binarynode left (left child) binarynode right (right child)
how do we evaluate expression trees
push the values onto a stack until you come across an operand
then calculate the last two values, push it back onto the stack
.contains
returns a boolean, is a recursive method boolean contains(Anytype x, BinaryNode t) if null, return false
int compareResult = x.compareTo(t.element)
if compareresult > 0 return cotains (x, t.left); if compareres8ult < 0 return contains(x, t.right); else return true //match
findMin
recursive, just the very left most node
findMin(binarynode t)
if t == null
return null
else if t.left == null
return t.left
return findmin(t.left)
insert
binarynode insert (anytype x, binarynode t) if t == null return new binarynode (x, null, null)
int compareresult = x.compareto(t.element)
if compareresult < 0 t.left = insert(x, t.left) if compareresult > 0 t.right = insert(x, t.right) else do nothing // this means that the number already exists in the binary tree
return t;
remove
if it has one child, just change the pointer from the target node to the child
if it has two children, the new parent is the smallest node of the right subtree
if(node.left !=null&& node.right !=null) {// two
childrennode.data = findMin(node.right).data;node.right =
remove(node.right, node.data);
AVL Tree
tree with a balance condition
single rotation
middle node becomes the parent, other two become the left or right children
double rotation
zig zag zig etc
first swap the bottom two nodes so it turns into a scenario where it becomes a single rotation
tree traversals
inorder, preorder, postorder
running time O(N)
printTree(binaryNode t)//inorder traversal if t != null printTree(t.left) system.out.println(t.element); printtree(t.right)