思路类似于“把二叉树打印成多行”,添加一个flag,表示从左到右还是从右到左,如果是从右到左就把tmp反转添加到result里。
代码:
class Solution:
    def Print(self , pRoot: TreeNode) -> List[List[int]]:
        # write code here
        queue = []
        result = []
        queue.append(pRoot)
        left_to_right = True
        while queue:
            num = len(queue)
            tmp = []
            for i in range(num):
                node = queue.pop(0)
                if node is None:
                    continue
                tmp.append(node.val)
                queue.append(node.left)
                queue.append(node.right)
            if tmp:
                if left_to_right:
                    result.append(tmp)
                else:
                    tmp.reverse()
                    result.append(tmp)
            left_to_right = not left_to_right
        return result

参考资料:
https://blog.nowcoder.net/n/2fba2cf6f43741e99f38d2169745a746?f=comment