









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
Trees
Root โ node with no parent Leaf โ all nodes with no children Interior โ all nodes with children Root node
Leaf nodes
Interior nodes
Trees
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
Tree Traversal
Tree Traversal
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
Tree Traversal Methods
Tree Traversal Methods
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 } }
Types of Binary Trees
Mostly 1 child / node Height = O(n) Similar to linear list
Mostly 2 child / node Height = O( log(n) ) Useful for searches
Degenerate binary tree
Balanced binary tree
Binary Search Trees
Value at node Smaller values in left subtree Larger values in right subtree Example X > Y X < Z
Binary Search Trees
Binary search trees
Non-binary search tree
Binary Tree Implementation
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 โ 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
Polymorphic Binary Tree Implement.
Example : Standard Binary Tree
Node X { left = Y; right = Z; }
Node Y { left = null; right = null; }
Node W { left = null; right = null; }
Node Z { left = null; right = W; }
Example : Polymorphic Binary Tree
NonEmpty X { left = Y; right = Z; }
NonEmpty Y { left = S; right = S; }
NonEmpty W { left = S; right = S; }
NonEmpty Z { left = S; right = W; }
EmptyTree S { }