Download Data Structures and Algorithms Lecture: Binary Trees, Heaps, and Binary Search Trees and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!
Data Structures and
Algorithms
LECTURE 09: BINARY TREES, HEAPS, BINARY SEARCH TREES
- Binary Trees
- Heaps
- Binary heap, Min/Max heaps
- Binary Search Trees
Contents
2
- ADS representing tree like hierarchy
- Each node has at most two children
- Children are called left and right
- The parent is also called source
Binary Tree
S L R
- Binary trees : the most widespread form
- Each node has at most 2 children ( left and right )
Binary Trees
5 17 9 15 6 5 8 Root node Left subtree Right child Left child
- Complete – nodes are filled top to bottom and left to right
Types of Binary Trees
7 17 9 15 6 5 8 (^13 ) 23
- Perfect – combines complete and full
- leafs are at the same level , other nodes have two children
Types of Binary Trees
8 17 9 15 6 5 8 13 42 23 (^7 3 1 31 96 )
- Fields and constructor: Solution: BT Traversals - Constructor 10 public class BinaryTree implements AbstractBinaryTree { private E key; private BinaryTree left; private BinaryTree right; public BinaryTree(E key, BinaryTree left, BinaryTree right) { this.key = key; this.left = left; this.right = right; }
Solution: BT Traversals - Print 11 Process Node Traverse Left Traverse Right public String asIndentedPreOrder(int indent) { String out = createPadding(indent) + getKey(); if (getLeft() != null) { out +="\n" + getLeft().asIndentedPreOrder(indent + 2); } if (getRight() != null) { out +="\n" + getRight().asIndentedPreOrder(indent + 2); } return out; }
- Left Root Right Binary Trees Traversal: In-order 17 9 25 (^31120 ) 3 9 11 17 20 25 31 inOrder (node) { if (node != null) { inOrder(node.left) print node.key inOrder(node.right) } }
- Left Right Root Binary Trees Traversal: Post-order 17 9 25 (^31120 ) 3 11 9 20 31 25 17 postOrder (node) { if (node != null) } postOrder(node.left) postOrder(node.right) print node.key } }
Heaps
Heap, Binary Heap
- Heap
- Tree-based data structure
- Stored in an array
- Heaps hold the heap property for each node:
What is Heap?
- Binary heap can be efficiently stored in an array
- Parent(i) = (i - 1) / 2
- Left(i) = 2 * i + 1; Right(i) = 2 * i + 2 Binary Heap – Array Implementation 19 heap and shape properties are satisfied 5 4 1 (^3 ) 5 4 1 3 2
- To preserve heap properties :
- Insert at the end
- Heapify element up
- Right: Max Heap
Heap Insertion
20 17 9 15 (^6 5 8 ) Satisfy heap property Promote while element > parent 25