从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树:[3,9,20,null,null,15,7]
3
/ \\
9 20
/ \\
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
DFS深度优先
我们使用一个队列来记录一个树,通过depth来记录每一次到达的树的深度,当当前的栈的大小和深度相同,那说明此时遍历到了更深一层,则需要向队列中新加一个空间。按深度对队列进行push。
var levelOrder = function (root) {
let res = []
getRes(root, 0, res);
return res;
function getRes(root, depth, res) {
if (!root) return null;
if (!res[depth]) res.push([]);
res[depth].push(root.val);
getRes(root.left,depth+1,res)
getRes(root.right,depth+1,res)
}
};
BFS广度优先
广度优先则是先遍历每一层,当当前层遍历完成之后再进行下一层的遍历。
var levelOrder = function (root) {
let res = []
if (!root) return res;
let queue = [];
queue.push(root);
while (queue.length) {
let temp = [];
for (let i = queue.length; i > 0; i--) {
let node = queue.shift()
temp.push(node.val)
node.left && queue.push(node.left)
node.right && queue.push(node.right)
}
res.push(temp)
}
return res;
};