Download Binary search tree and its explaination and more Slides Data Structures and Algorithms in PDF only on Docsity!
Data Structures and Algorithms
LECTURE 14 – BINARY TREES
General / Binary Tree
- General tree – a node can have any number of children
- Binary tree – a node can have at most two children
Binary Search – (Search 13)
BINARY TREE
Binary Search Tree
- A fundamental data structure in computer science
- Used for rapidly storing and retrieving data
- Composed of nodes which store data and links to up to two other child nodes
- The nodes on the left have a lesser key values (i.e., the value used to search for a Node
in the tree), and the nodes on the right have a higher key value
- Corollary:
- Leaves on the farthest left of the tree have the lowest values
- Leaves on the right of the tree have the greatest values
Why?
- Arrays:
- Arrays can achieve efficient searching, e.g., binary search
- However, inefficient insertion and deletion algorithms that require shifting data in the array
- Linked Lists
- Efficient insertions and deletions
- However, search algorithms are sequential which are inefficient
- Binary Search Tree
- Efficient search, insertion, and deletion
Examples
A Binary Search Tree
Examples
A Binary Search Tree What about this one?
Examples
- None of them is a Binary Search Tree.
BST Complexity
- Number of nodes in the above given “complete” BST = n
- Height of BST = h
- Given the of height h, the value of n, i.e., all nodes in the tree are:
- n = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 …. + 2h
BST Implementation – Node
- See Handout for Source Code – “BST” //BST = Binary Search Tree class BSTNode { public : int key; BSTNode left, right; BSTNode( int el = 0, BSTNode l = NULL, BSTNode r = NULL) { key = el; left = l; right = r; } };
BST Implementation - Class class BST { public : BSTNode* root; BST(): root(NULL) {} //destroy routines ~BST(); void clear(BSTNode* ptr); //insertion routines void insert( int A); void insert_node( int B, BSTNode* &node1); //traversal routines void visit(BSTNode* node) { cout<<" :: "<<node->key<<" :: "<<endl; } void breadth_first(); void depth_first(); void preorder(BSTNode* node); void inorder(BSTNode* node); //searching routines int search( int A); BSTNode* search_node(BSTNode* node, int B); //deletion routines void deletenode( int A); void deletebycopying(BSTNode* &node2); };
BST Operations - Insertion
- A Recursive Call
- Base case
- General case
- Choose the left or right subtree
BST Operations - Searching
- A Recursive Call
- Base case
- The Node is found whose key equals the required
- Return the Node’s reference
- General case
- If the required key is less than the current node’s key, search Left Subtree
- If the required key is greater than or equal to the current node’s key. search Right Subtree