Exemple #1
0

class Solution:
    def levelOrder(self, root: TreeNode) -> list:

        if root == None:
            return []

        res = []
        queue = [root]

        while queue != []:
            nextQueue = []
            currentLayer = []
            while queue != []:
                currentNode = queue.pop()
                currentLayer.append(currentNode.val)
                if currentNode.left != None:
                    nextQueue.insert(0, currentNode.left)
                if currentNode.right != None:
                    nextQueue.insert(0, currentNode.right)
            queue = nextQueue
            res.append(currentLayer)

        return res


test = Solution()
tree = [3, 9, 20, "null", "null", 15, 7]
root = createTreeNodeByLayerSeq(tree)
print(test.levelOrder(root))
                    queue.insert(0, currentNode.left)
                    queue.insert(0, currentNode.right)
            return outputSeq

        layerSeq = BFSBinaryTree(root)
        # print(layerSeq)
        outputSeq = []
        SeqLen = len(layerSeq)
        LayerNum = math.ceil(math.log(SeqLen + 1, 2))
        seqIdx = 0
        for i in range(LayerNum):
            currentLayer = []
            while seqIdx < SeqLen and seqIdx + 1 <= (int(math.pow(2, i + 1)) -
                                                     1):
                # print(layerSeq[seqIdx], seqIdx + 1, i+1, math.pow(2, i + 1) - 1)
                if i % 2 == 0 and layerSeq[seqIdx] != "null":
                    currentLayer.append(layerSeq[seqIdx])
                elif layerSeq[seqIdx] != "null":
                    currentLayer.insert(0, layerSeq[seqIdx])
                seqIdx += 1

            if currentLayer != []:
                outputSeq.append(currentLayer)

        return outputSeq


test = Solution()
seq = [1, 2, "null", 3, "null", 4, "null", 5]
head = createTreeNodeByLayerSeq(seq)
print(test.levelOrder(head))