32.III.从上到下打印二叉树III

题目

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:

给定二叉树: [3,9,20,null,null,15,7],

     3
    / \
   9  20
     /  \
    15   7

返回其层次遍历结果:

 [
   [3],
   [20,9],
   [15,7]
 ]

提示:

节点总数 <= 1000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

func levelOrder(_ root: TreeNode?) -> [[Int]] {
    guard let r = root else {
        return []
    }

    var queue: [TreeNode] = []
    var queueB: [TreeNode] = []
    var toBePrint = 0
    var nextLevelCount = 0
    var result: [[Int]] = []
    var flag = true

    queue.append(r)
    toBePrint += 1

    var temp = Array(repeating: 0, count: queue.count)

    while queue.isEmpty == false {
        let first = queue.removeFirst()
        temp[flag ? (temp.count - toBePrint) : (toBePrint - 1)] = first.val
        toBePrint -= 1

        if let left = first.left {
            queueB.append(left)
            nextLevelCount += 1
        }

        if let right = first.right {
            queueB.append(right)
            nextLevelCount += 1
        }

        if toBePrint == 0 {
            result.append(temp)
            queue = queueB
            temp = Array(repeating: 0, count: nextLevelCount)

            toBePrint = nextLevelCount
            nextLevelCount = 0
            queueB = []
            flag.toggle()
        }
    }

    return result
}

Last updated