Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
我的想法是广度优先遍历,把所有同层的找出来,值存起来放到结果数组中,再找下一层:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if (!root) {
return [];
}
var result = [[root.val]];
var seachingNodes = [root];
var tempNodes,vals,num;
while (seachingNodes.length!==0) {
//console.log(seachingNodes);
tempNodes = [];
vals = [];
num = seachingNodes.length;
for (var i = 0; i < num; i++) {
if (seachingNodes[i].left) {
tempNodes.push(seachingNodes[i].left);
vals.push(seachingNodes[i].left.val);
}
if (seachingNodes[i].right) {
tempNodes.push(seachingNodes[i].right);
vals.push(seachingNodes[i].right.val);
}
}
if (vals.length!==0) {
result[result.length]=(vals);
}
seachingNodes = tempNodes;
}
return result;
};