Binary Tree
Idea Like You Are 10
A binary tree is a tree where each node can have:
- no child
- one child
- or two children
The two sides are called:
- left child
- right child
Picture
Types Of Binary Trees
Full Binary Tree
Every node has either 0 or 2 children.
Complete Binary Tree
All levels are full except maybe the last, and the last fills from left to right.
Perfect Binary Tree
All internal nodes have 2 children and all leaves are at the same level.
Balanced Binary Tree
Tree height stays fairly small.
Operations
Traversals
Preorder
Root, Left, Right
Inorder
Left, Root, Right
Postorder
Left, Right, Root
Level Order
Uses queue.
Insertion In General Binary Tree
One common method inserts at the first empty place in level order.
Deletion In General Binary Tree
One common method:
- find node to delete
- find deepest rightmost node
- copy deepest node's data
- delete deepest node
Complexity Analysis
| Operation | Time |
|---|---|
| Traversal | O(n) |
| Search | O(n) |
| Insert (level order) | O(n) |
| Delete | O(n) |
Why?
In a normal binary tree there is no ordering rule like BST.
So you may need to inspect many nodes.