Reputation: 13
I've been trying to write a method to insert nodes in a binary tree in level order(left to right) and it only inserts values in first node(root). Here's the code i hope you can fix it!!!
class TreeNode{
int item;
TreeNode left=null;
TreeNode right=null;
public TreeNode(int item){
this.item=item;
}
}
class Tree{
public void insert(int item) {
Queue<TreeNode> q = new LinkedList<>();
if(root==null){
root=new TreeNode(item);
temp=root;
q.offer(temp);
}
else{
while (!q.isEmpty()) {
temp = q.peek();
if (temp.left == null) {
temp.left = new TreeNode(item);
break;
}
if (temp.right == null) {
temp.right = new TreeNode(item);
break;
} else{
q.offer(temp.left);
q.offer(temp.right);
q.poll();}
}
}}}
Upvotes: 1
Views: 162
Reputation: 2303
You can use this code, you have to assign the temp
to root
every time you call the insert
method
public void insert(int item) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
if(root==null){
root = new TreeNode(item);
} else {
temp = root;
q.offer(temp);
while (!q.isEmpty()) {
temp = q.peek();
if (temp.left == null) {
temp.left = new TreeNode(item);
break;
}
if (temp.right == null) {
temp.right = new TreeNode(item);
break;
} else{
q.offer(temp.left);
q.offer(temp.right);
q.poll();
}
}
}
}
Upvotes: 1