Trees Flashcards
What is a binary tree?
A tree whose elements have at most 2 children (left and right child)
How are binary trees stored in memory?
Each node has a pointer to parent (or NULL/itself if root), pointer to left/right child (or NULL/itself if there isn’t one), and a value representing the item stored in the node
How do you search a binary tree?
Start at the root and search the tree level-by-level (top to bottom, left to right)
This has time complexity O(n)
What is a binary search tree?
A binary tree where for every node (with value v), all elements in the left sub-tree are smaller than v and all elements in the right sub-tree are bigger than v
Preorder vs inorder vs postorder tree traversal
Preorder = print(root), preorder(left), preorder(right)
Starts with root, goes all the way left, ends with rightmost
Inorder = preorder(left), print(root), preorder(right)
Starts with leftmost, ends with rightmost, items in sorted order
Postorder = preorder(left), preorder(right), print(root)
Starts with leftmost, ends with root
Inserting into a BST
Call the .insert() function on the root
This function:
Compares the new value to the root
If it’s less than the root, recurses into the left subtree
If it’s greater than the root, recurses into the right subtree
If the left/right subtree doesn’t exist, it appends the new value there
Searching a BST
Call the .lookup(n) function on the root
If this is a match, return it and its parent
If our target is smaller, recurse into the left sub-tree, otherwise recurse into the right sub-tree
Deleting from a BST
Call root.delete(n)
No children: simply remove n
One child: Transfer child’s value to n and then delete child
Two children: Find the smallest node v that’s bigger than n, copy v’s data into n, and then delete v
Time complexity of searching, inserting and deleting
Average: O(h) = O(log(n))
Worst: O(n)
Finding the smallest element in a BST
Always go left
Finding the smallest element bigger than a given node in a BST
Start at that node, go right once and then always go left. Stop when you hit NULL.
What is an AVL tree?
One where a given node’s subtrees do not differ in height by more than 1
Tree.LeftRotate(x)
Remove x.right.left and store for later
Replace x with x.right
The new x.left should now be empty
x.left = old x, left: old x.left, right: old x.right.left
What is trinode restructuring
A combination of rotations, applied to a parent, child, and grandchild (z, y, x) depending on whether the child and grandchild are on the same side
Trinode restructuring: single rotation (child and grandchild on same side)
Assuming both right:
Tree.LeftRotate(z)