John Mavrick's Garden

Search IconIcon to open search

Last updated Unknown

Status: Tags: #cards/cmpt225/dataStructures/trees Links: Binary Tree


Binary Search Trees

Principles

Utilities

Types

Degenerate binary search tree ?

Time Efficiency

Self-balancing binary search tree

Implementations

Array-Based 1

Visual Representation

Image from Gyazo

Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class BSTNode {
	private:
		ElementType element; // element stored in tree node
		int leftChild; // index to left child/subtree
		int rightChild; // index to right child/subtree
}

class BinarySearchTree {
	private:
		BSTNode myTree[CAPACITY];// array of tree elements
		int root; // index of root
		int elementCount; // number of elements
}

Array-Based 2

Visual Representation

Image from Gyazo

Code
1
2
3
4
5
class BinarySearchTree {
	private:
		ElementType myTree[CAPACITY]; // array of elements
		int elementCount; // number of elements
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class BSTNode { 
	private:
		ElementType element; // element stored in tree
		node BSTNode* leftChild; // link to left child/subtree
		BSTNode* rightChild; // link to right child/subtree 
}

class BinarySearchTree {
	private:
		BSTNode* root; // root of tree
		int elementCount; // number of elements
}

Public Interface

insert()

insertR()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Node* BST::insertR(Node* subTree, Node* newNode){
	if (subTree == NULL) return newNode; // Base case
	else
	{
		if (subTreegetElement() > newNodegetElement())
		subTreesetLeft(insertR(subTreegetLeft(), newNode));
		else
		subTreesetRight(insertR(subTreegetRight(),newNode));
	return subTree;
} // end if
}

Functions

find

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
BTnode_t* recursive_find (BTnode_t* root, int item) {
	if ( root == NULL )
		return NULL;
	if (rootvalue == item)
		return root;
	if ( rootvalue > item )
		return find( rootleft, item) ;
	else // if ( root→data < item )
		return find( rootright, item) ;
}


BTnode_t* iterative_find (BTnode_t* root, int item) {
 BTnode_t* current = root;
	while ( current != NULL && currentvalue != item) {
		if (currentvalue > item )
			 current = currentleft;
		else  	// current→data < item
			current = currentright;
	}
	return current;
}

remove


Backlinks

1
list from Binary Search Trees AND !outgoing(Binary Search Trees)

References:

Created:: 2021-11-15 14:52


Interactive Graph