



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




One-to-many relationship between elements
Contains data Referred to by only 1 (parent) node Contains links to any number of (children) nodes
Parent node
Children nodes
Root ⇒ node with no parent Leaf ⇒ all nodes with no children Interior ⇒ all nodes with children Root node
Leaf nodes
Interior nodes
Sibling ⇒ node with same parent Descendent ⇒ children nodes & their descendents Subtree ⇒ portion of tree that is a tree by itself ⇒ a node and its descendents
Subtree
Siblings
Level ⇒ is a measure of a node’s distance from root Definition of level If node is the root of the tree, its level is 1 Else, the node’s level is 1 + its parent’s level Height (depth) ⇒ max level of any node in tree
Height = 3
Tree with 0–2 children per node Left & right child / subtree
Binary Tree
Left Child
Parent
Right Child
Visit every node in binary tree
Depth first Preorder ⇒ parent before children Inorder ⇒ left child, parent, right child Postorder ⇒ children before parent Breadth first ⇒ closer nodes first
BFS(Node n) { Queue Q = new Queue(); Q.enqueue(n); // insert node into Q while ( !Q.empty()) { n = Q.dequeue(); // remove next node if ( !n.isEmpty()) { visit(n); // visit node Q.enqueue(n.Left()); // insert left subtree in Q Q.enqueue(n.Right());// insert right subtree in Q } }
88
44
17 78
32 50
48 62
Sorted order!
Example Binary Searches
10 > 2, left
5 > 2, left
2 = 2, found
5 > 2, left
2 = 2, found
Example Binary Searches
10 < 25, right
30 > 25, left
25 = 25, found
5 < 25, right
45 > 25, left
30 > 25, left
10 < 25, right
25 = 25, found
Binary Search Properties
Proportional to height of tree Balanced binary tree O( log(n) ) time Degenerate tree O( n ) time Like searching linked list / unsorted array
Ability to compare key values
Binary Search Tree Construction
Insertion Deletion
Smaller values in left subtree Larger values in right subtree
Binary Search Tree – Insertion
O( log(n) ) operation for balanced tree Insertions may unbalance tree
Example Insertion
10 < 20, right
30 > 20, left
25 > 20, left
Insert 20 on left
Binary Search Tree – Deletion
O( log(n) ) operation for balanced tree Deletions may unbalance tree
Example Deletion (Leaf)
10 < 25, right
30 > 25, left
25 = 25, delete
Example Deletion (Internal Node)
Replacing 10 with largest value in left subtree
Replacing 5 with largest value in left subtree
Deleting leaf
Example Deletion (Internal Node)
Replacing 10 with smallest value in right subtree
Deleting leaf Resulting tree
Building Maps w/ Search Trees
Each non-empty node contains Key Value Left and right child
Generic type <K extends Comparable
Polymorphic Binary Search Trees
Rather than null
Without checking for null Get empty or nonempty functionality Selected by type of tree node