解题思路
层序遍历顺序就是广度优先遍历。
不过在遍历时候需要记录当前节点所处层级,方便将其添加到不同的数组中。
解题步骤
广度优先遍历二叉树。
遍历过程中,记录每个节点的层级,并将其添加到不同的数组中。
代码:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if(!root) return [];
const queue = [[root,0]];
const res = [];
while(queue.length){
const [n,level] = queue.shift();
if(!res[level]){
res.push([n.val]);
}else {
res[level].push(n.val);
}
n.left && queue.push([n.left,level+1]);
n.right && queue.push([n.right,level+1]);
}
return res;
};
102. 二叉树的层序遍历
解题思路
层序遍历顺序就是广度优先遍历。
不过在遍历时候需要记录当前节点所处层级,方便将其添加到不同的数组中。
解题步骤
广度优先遍历二叉树。
遍历过程中,记录每个节点的层级,并将其添加到不同的数组中。
代码: