Trees, Heaps, Graphs
Last updated
Was this helpful?
Last updated
Was this helpful?
Depth of a node – number of ancestors (exclude itself) / number of edge to the root
Height of a tree – maximum depth of any node
Traversal
Preorder: a node is visited before its descendants
Postorder: a node is visited after its descendants
Each internal node has at most two children
Children of a node are an ordered pair
Proper Binary Tree
if each node has 0 or 2 children
Traversal
Inorder: left -> root -> right
Preorder: root -> left -> right
Postorder: left -> right -> root
Left < Root < Right
Search: cut sub-tree in half, determine which half the key would be in
Insertion: expand an internal node / update value
Deletion: replace with its left right-most node value, delete left right-most node
Performance
Find, insert, remove – O(n) worst case (all node in one side)
Find, insert, remove – O(log n) best case (balanced tree)
First balanced binary search tree
Heights of siblings can differ by at most 1
Minimize single look up time, not exceed O(log n)
Useful in multithreaded environments
Self-balancing BST
3 Types of Splay Steps
Zig-Zig
Zig-Zag
Zig
Preferred for lots search, less insertion and deletion (cause rotations)
Minimize total lookup time.
Easier to implement, compare to AVL tree.
Self-balancing BST
Each node has colour either red or black
No two adjacent red nodes
Every path from a node to any its descendant Null node has same number of black nodes
Preferred for lots insertions and deletions
Binary tree with additional rules
Complete binary tree – last node of the heap is the rightmost node of depth h
Build Heap: Botton up heap construction – O(n)
Insertion: upheap – O(log n)
Deletion: downheap – O(log n)
Parent node values are greater than their children
Parent node values are less than their children
Traversing down through one branch to the leaf, then back to "trunk".
Use Stack – O(n)
Search through a tree one level at a time
Use Queue – O(n)