I have this binary tree
3
/ \
9 20
/ \
15 7
i want to print its level order traversal in this format
[
[3],
[9,20],
[15,7]
]
so i wrote this code using a queue and two lists
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<TreeNode>();
List<Integer> list=new ArrayList<>();
List<List<Integer>> res=new LinkedList<>();
if(root!=null)
{
queue.add(root);
}
while(!queue.isEmpty())
{
int size=queue.size();
for(int i=0;i<size;i++)
{
TreeNode tempNode=queue.poll();
list.add(tempNode.val);
if(tempNode.left!=null)
queue.add(tempNode.left);
if(tempNode.right!=null)
queue.add(tempNode.right);
}
res.add(list);
list.clear();
}
return res;
}
}
but when i check the output it returns
[[],[],[]]
i have spent more than 1 hour to debug the problem and i am convinced that my code is correct (which is not!) i dont know what is clearing the res list after i am adding the data to it. please help me to fix the error.
i believe list.clear() also clears the added list item in res.
of this is so then suppose
x=34;
list.add(x);
x=45;
System.out.println(list); // it will still print [34]
but using list of list and after adding item to it and if you modify inner list.. it also modifies your list of list . why ?
int x=3;
li.add(x);
x=45;
res.add(li);
System.out.println(li);
li.remove(0);
li.add(23);
System.out.println(res);