binary tree binary add 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: 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";
}