binary search tree insertion code example
Example 1: binary search tree insert java
public static Node insert(Node root, int x){
if (root == null)
return new Node(x);
else if(x>root.getData())
root.setRightChild(insert(root.getRightChild(),x));
else
root.setLeftChild(insert(root.getLeftChild(),x));
return root;
}
Example 2: insertion in binary tree
# Python program to insert element in binary tree
class newNode():
def __init__(self, data):
self.key = data
self.left = None
self.right = None
""" Inorder traversal of a binary tree"""
def inorder(temp):
if (not temp):
return
inorder(temp.left)
print(temp.key,end = " ")
inorder(temp.right)
"""function to insert element in binary tree """
def insert(temp,key):
if not temp:
root = newNode(key)
return
q = []
q.append(temp)
# Do level order traversal until we find
# an empty place.
while (len(q)):
temp = q[0]
q.pop(0)
if (not temp.left):
temp.left = newNode(key)
break
else:
q.append(temp.left)
if (not temp.right):
temp.right = newNode(key)
break
else:
q.append(temp.right)
# Driver code
if __name__ == '__main__':
root = newNode(10)
root.left = newNode(11)
root.left.left = newNode(7)
root.right = newNode(9)
root.right.left = newNode(15)
root.right.right = newNode(8)
print("Inorder traversal before insertion:", end = " ")
inorder(root)
key = 12
insert(root, key)
print()
print("Inorder traversal after insertion:", end = " ")
inorder(root)
Example 3: binary tree search
void searchNode(Node *root, int data)
{
if(root == NULL)
{
cout << "Tree is empty\n";
return;
}
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node *temp = q.front();
q.pop();
if(temp->data == data)
{
cout << "Node found\n";
return;
}
if(temp->left != NULL)
q.push(temp->left);
if(temp->right != NULL)
q.push(temp->right);
}
cout << "Node not found\n";
}
Example 4: insert binary search tree
void BSNode::insert(std::string value) {
if (this->_data == value) {
_count++;
return;
}
if (this->_data > value) {
if (this->getLeft() == nullptr) {
this->_left = new BSNode(value);
}
this->getLeft()->insert(value);
return;
}
if (this->getRight() == nullptr) {
this->_right = new BSNode(value);
return;
}
this->getRight()->insert(value);
}