Given a binary tree and a key, insert the key into the binary tree at first position available in level order.
The idea is to do iterative level order traversal of the given tree using queue. If we find a node whose left child is empty, we make new key as left child of the node. Else if we find a node whose right child is empty, we make new key as right child. We keep traversing the tree until we find a node whose either left or right is empty.
// C# program to insert element in binary tree
/* A binary tree node has key, pointer to
left child and a pointer to right child */
public class Node
public int key;
public Node left, right;
public Node(int key)
this.key = key;
left = null;
right = null;
static Node root;
static Node temp = root;
/* Inorder traversal of a binary tree*/
static void inorder(Node temp)
if (temp == null)
Console.Write(temp.key + ” “);
/*function to insert element in binary tree */
static void insert(Node temp, int key)
// Do level order traversal until we find
// an empty place.
while (q.Count != 0)
temp = q.Peek();
if (temp.left == null)
temp.left = new Node(key);
if (temp.right == null)
temp.right = new Node(key);
// Driver code
public static void Main(String args)
root = new Node(10);
root.left = new Node(11);
root.left.left = new Node(7);
root.right = new Node(9);
root.right.left = new Node(15);
root.right.right = new Node(8);
Console.Write(“Inorder traversal before insertion:”);
int key = 12;
Console.Write(“\nInorder traversal after insertion:”);
// This code is contributed by Rajput-Ji
Inorder traversal before insertion: 7 11 10 15 9 8 Inorder traversal after insertion: 7 11 12 10 15 9 8
This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Level order traversal in spiral form