问题
解决方案
var levelOrder = function (root) {
//定义结果集数组
let result = [];
if (root) {
//因为期望结果是分层数组输出的,区分层次定义父层与子层
let parent = [];
let children = [];
//暂存当前层的val值
let tmpCache = [];
parent.push(root)
while (!!parent.length) {
//出栈
let current = parent.shift();
tmpCache.push(current.val);
//如果当前节点存在,把左右节点暂存到children数组中
if (current.left) {
children.push(current.left);
}
if (current.right) {
children.push(current.right);
}
//如果parent数组长度为0,说明当前层遍历结束,做相应的处理
if (parent.length === 0) {
if (tmpCache.length) {
result.push(tmpCache);
}
tmpCache = [];
parent = children;
children = []
}
}
}
return result;
};