题目
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
队列按情况反转row
function Print(pRoot) {
// write code here
if (!pRoot) {
return []
}
let result = []
let queue = []
let vrse = false
queue.push(pRoot)
while (queue.length > 0) {
let len = queue.length
let row = []
for (let i = 0; i < len; i++) {
let shiftItem = queue.shift()
if (shiftItem.left) {
queue.push(shiftItem.left)
}
if (shiftItem.right) {
queue.push(shiftItem.right)
}
row.push(shiftItem.val)
}
if (vrse) {
reverse(row)
result.push(row)
} else {
result.push(row)
}
vrse = !vrse
}
return result
}
function reverse(arr) {
let i = 0
let j = arr.length - 1
while (i < j) {
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i++
j--
}
}