Trees Flashcards
What is a complete binary tree?
BinTree with all levels full, except bottom level. Last level is filled starting from the left.
What is a full binary tree?
BinTree where all nodes have 2 children, other than the leaves
how is the height of a tree calculated?
the max level of all nodes
how is the level of a node calculated?
numbers of edges from root node!
What are the 2 properties of a (min/max) binary heap?
what are the 2 properties referred to as?
- [shape property] complete binary tree structure
- [heap property] for min: parents always <= children
for max: parents always >= children
When representing bin-heaps with arrays, which index do you start with for the root node?
start with index 1, instead of index 0
How do you find the index of a child?
My child is 2x me
left child = 2p
right child = 2p + 1
How do you insert a new value into the binheap list?
append to end of list, then switch values to maintain heap property
How do you maintain heap property once you’ve inserted new value to end of list?
Compare value with value of parent;
for min BinHeap, if child smaller than parent, switch child and parent, etc.
When we remove the root node (min/max value), how do we preserve the heap property?
move the last item in the list to the front of list, then percolate down
How do you percolate down to preserve heap property?
compare parent to 2 children, switch with the child that is larger than parent and other child (max heap)
What’s the binary search tree (BST) property?
all left subtree values to a node are smaller than the value in the node
all right subtree values to a node are greater than the value in the node
How do preorder, postorder and inorder BST traversal work?
Do this recursively, starting with the root node & its children
Preorder: parent - left child - right child
Inorder: left child - parent - right child
Postorder: left child - right child - parent
For the BST, what’s an algorithm for finding a node corresponding to a particular value?
(1st pseudo code, 2nd Python code)
check if first node’s value is EQUAL to the value, if yes, return the node:
else: if node’s value is larger than the value we’re finding, recursively perform function on left child
elif:
do opposite:
else: return None
What’s an algorithm for inserting a node with a value into an existing BST?
(1st pseudo code, 2nd Python code)
1st:
check if the value is the same as the value of the current node (we can only insert unique values?)
if yes, return (do nothing)
2nd:
check if the value is smaller than the value in the current node
if it is, check if a left child exists:
if yes, recursively call inserting function, using that left child as current node i.e. self.left.insert(value)
if no, make new left child BST object with self.left = BST(value, parent = self)
repeat for checking if the value is larger than the value in the current node