Tree - Binary Search Tree
Tree - Binary Search Tree
2
Binary Search Tree
A Binary Search Tree is a binary tree, which is
either empty or satisfies the following
properties :
3
Example
Here the root node information
is 50.
5
Create BST
A BST is constructed by the repeated insertion
of new nodes to the tree structure.
Inserting a node in to a tree is achieved by
performing two separate operations.
The tree must be searched to determine where the
node is to be inserted.
Then the node is inserted into the tree.
6
BST Structure
struct bst
{
int data;
struct bst *left;
struct bst *right;
} *root=NULL;
7
Finding Node
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no
match,
{
if(key < current.iData) // go left?
current = current.leftChild;
else
current = current.rightChild; // or go right?
if(current == null)
return null; // didn’t find it
}
return current; // found it
}
8
Inserting Node
public void insert(int id, double dd)
{
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
{
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
{
parent = current;
9
Insertion
if(id < current.iData) // go left?
{
current = current.leftChild;
if(current == null)
{ // insert on left
parent.leftChild = newNode;
return;
}
} // end if go left
else // or go right?
{
10
Insertion
current = current.rightChild;
if(current == null)
{ // insert on right
parent.rightChild = newNode;
return;
}
} // end else go right
} // end while
} // end else not root
} // end insert()
11