To prove safety OFFER ---- 32-3, the order of the zigzag print binary tree (js achieve)

topic

Implement according to a zigzag print function binary tree, i.e., left to right, the first print line of the second layer in order to print from right to left, the third line from left to right order of printing, in other rows forth.


Thinking

Queue the circumstances reversed 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--
    }
}

Guess you like

Origin blog.csdn.net/qq_40816360/article/details/94589520