Ruby solution

  • 0

    To effectively traverse the binary tree we need to have an array that holds the current level of nodes. Under each level, we also need a temp array to hold all the values of the nodes.

    The tricky part is the "zigzag", where we need to travel from left to right on one layer, and then right to left on another layer. However, we can assign a flag variable and toggle the flag during each iteration by doing flag = flag * -1

    # @param {TreeNode} root
    # @return {Integer[][]}
    def zigzag_level_order(root)
        return [] if root == nil
        res, queue, flag = [], [root], 1
        while (queue != [])
            temp = []
            num = queue.size
            num.times do
                node = queue.shift
                temp << node.val
                queue << node.right if node.right != nil
                queue << node.left if node.left != nil
            temp = flag == -1 ? temp : temp.reverse
            res += [temp]
            flag = flag * -1

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.