Binary Trees Flashcards
Difference between Binary Trees and Binary Search Trees
Binary Search Trees (BST) are a variation of binary trees with a sorted property to them. The property tells us that every left child must be smaller than its parent and every right child must be greater than its parent. BSTs do not allow duplicates.
What advantages does a Binary Search Tree (BST) have over arrays?
Both can search in O(logn), but BSTs can add/del in O(logn) (for balanced trees) vs O(n) for arrays. If unbalanced, O(n).
How is BST search implemented
Best done using recursion. You could traverse iteratively, however, that requires maintaining a stack, which is a lot more complicated.
How are BST insert/delete implemented?
For insert, traverse the tree to the correct spot and insert it.
For delete, if there is one child, replace the deleted node with the child. If two children, replace the node with the lesser child. Insert and delete are O(logn) for balanced trees, but can be O(n) in the worst unbalanced case.
Depth First Search (DFS)
This search method does to the bottom of the tree first. Best implemented with recursion. Three methods can be used:
Preorder - Visits parent, left child, right child
Inorder - Visits left child, parent, right child (sorted order)
Postorder - Visits left child, right child, parent.
Runs in O(n) because it visits every node in the tree
Breadth First Search (BFS)
Best implemented iteratively. Uses a deque. Adds all the nodes at each level to the deque, processes them, then adds all of the next level. O(n)