![b5226e4bce37dac5abd3ca0577e91158.png](https://i-blog.csdnimg.cn/blog_migrate/d87332aa524a4a6212e8cc989b56d5a6.png)
题目
![b44b76b1c276ac72c952c338356a8c75.png](https://i-blog.csdnimg.cn/blog_migrate/4425ae41c556ce233938f8a1adf9622c.jpeg)
这道题重点复习了一个思路:
- 看到BFS就要想到队列
- 看到DFS就要想到栈
解题
栈
class Node {
constructor(val, children) {
this.val = val;
this.children = children;
}
}
/**
* @param {Node} root
* @return {number[][]}
*/
var levelOrder = function (root) {
// 栈-迭代
const output = [];
const stack = [];
let helpStack = []
let loopIndex = 0;
if (!root) {
return output;
}
stack.push(root);
while (stack.length) {
const top = stack.pop();
if (!output[loopIndex]) {
output[loopIndex] = [];
}
output[loopIndex].push(top.val);
if (Array.isArray(top.children) && top.children.length) {
helpStack.push(...top.children);
}
if (!stack.length) {
loopIndex++
stack.push(...helpStack.reverse())
helpStack = []
}
}
return output;
};
队列
严格意义上上面选择栈其实不适合,因为栈更加适合DFS。而我们题目中的是层序遍历,从上往下,从左到右即BFS。
class Node {
constructor(val, children) {
this.val = val
this.children = children
}
}
/**
* @param {Node} root
* @return {number[][]}
*/
var levelOrder = function(root) {
const output = []
const queue = []
if (!root) {
return output
}
queue.push(root)
while(queue.length) {
// 记录当前每层的val
const loop = []
// 每次只循环当前层的长度
const size = queue.length
for (let i = 0; i < size; i++) {
const head = queue.shift()
loop.push(head.val)
if (Array.isArray(head.children)) {
queue.push(...head.children)
}
}
output.push(loop)
}
return output
};
优化版
class Node {
constructor(val, children) {
this.val = val
this.children = children
}
}
/**
* @param {Node} root
* @return {number[][]}
*/
var levelOrder = function(root) {
// 还有一种比较巧的方法
// 队列法
const output = []
if (!root) {
return output
}
let queue = [root]
while(queue.length) {
// 存储每层的vals
const curLoopVals = []
// 存储下一层的nodes
const nextLoopNodes = []
for (let i = 0; i < queue.length; i++) {
let curNode = queue[i]
curLoopVals.push(curNode.val)
if (curNode.children && curNode.children.length) {
nextLoopNodes.push(...curNode.children)
}
}
output.push(curLoopVals)
// 交换
queue = nextLoopNodes
}
return output
};
递归
class Node {
constructor(val, children) {
this.val = val
this.children = children
}
}
/**
* @param {Node} root
* @return {number[][]}
*/
var levelOrder = function(root) {
// 递归
const output = []
// 递归就说扫描每个节点,并将其值存储到对应的层
const swapNode = (node, level) => {
if (output.length <= level) {
output[level] = []
}
output[level].push(node.val)
if (Array.isArray(node.children)) {
for (let i = 0; i < node.children.length; i++) {
console.log(level)
swapNode(node.children[i], level + 1)
}
}
}
if (root) {
swapNode(root, 0)
}
return output
};