JavaScript实现按之字形顺序打印二叉树
按之字形顺序打印二叉树
http://www.nowcoder.com/questionTerminal/91b69814117f4e8097390d107d2efbe0
实现思路:
这道题其实就是从上到下分行打印二叉树的升级版本。只消定义一个变量来判断当前行是奇数行还是偶数行。(假设二叉树的第一行为0,即偶数行)。
构造一个临时数组容器temp,存放二叉树中每一行的节点。如果为奇数行,就使用栈来存储(push方法),如果为偶数行,就使用队列来存储(unshift方法)。
遍历完每一行后,就将结果temp存储在res中。最终输出res。
JavaScript代码实现如下:
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
function Print(pRoot)
{
if(!pRoot) {
return []
}
var queue = [], res = [], temp = [],
node, level = 0, toBePrinted = 1, isEven = true;
queue.push(pRoot);
while(queue.length) {
node = queue.shift();
// 判断当前行为奇数行还是偶数行
if(isEven) {
temp.push(node.val);
} else {
temp.unshift(node.val);
}
// 计算每一行的元素个数
if(node.left) {
queue.push(node.left);
level++;
}
if(node.right) {
queue.push(node.right);
level++;
}
toBePrinted--;
// 判断当前行是否全部输出完毕
if(toBePrinted === 0) {
res.push(temp);
temp = [];
toBePrinted = level;
level = 0;
isEven = !isEven;
}
}
return res;
}
module.exports = {
Print : Print
};
字节跳动公司福利 1328人发布
