# My JS code doesn't exert in the right way

• I've written my code like this :

``````var tree = [];

/**
* Definition for binary tree
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/

/**
* @param {TreeNode} root
* @param number the level of root node
*/
var bfs = function(root, level) {

//var tmp = [];

if(root === null) return ;
else {
if(tree.length < level+1)tree[level] = [];
tree[level].push(root.val);
}

bfs(root.left, level+1);
bfs(root.right, level+1);
};

/**
* @param {TreeNode} root
* @returns {number[][]}
*/
var levelOrder = function(root) {

bfs(root, 0);
return tree;
};
``````

Then sumitted, it doen's pass the test case :

``````Input: 	{1,2}
Output: 	[[1,1],[2]]
Expected: 	[[1],[2]]
``````

I added codes next to it to test :

``````function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}

var l = new TreeNode(2);
var r = new TreeNode(1);
r.left = l;
levelOrder(r);
console.log(tree);
``````

Then test it on my computer (Node version : v0.10.33), it printed :

``````# node ./levelOrder.js
[ [ 1 ], [ 2 ] ]
``````

It was the right result. Plese who can tell why, thx! (Sorry for my poor English ^_^)

• All test results are being dumped into `tree`. One test will generate the right answer.

You need to either put `tree` in the right scope, or, clear it at the beginning of `levelOrder`

• Put your tree & bfs in your levelOrder function. You can call your bfs inside levelOrder function.

Here is the solution that works:

``````function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}

var levelOrder = function(root) {
var result = [];
var searchTreeNode = function(node, level){
if(node === null) {
return;
} else {
if(result.length < level+1){
result[level] = [];
}
result[level].push(node.val);
}
searchTreeNode(node.left, level+1);
searchTreeNode(node.right, level+1);
}
searchTreeNode(root, 0);
return result;
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.