Day 23: BST Level-Order Traversal

  • + 0 comments

    Since we can't use Python's collections.deque and the O(1) popleft function, it's actually more effecient to just maintain a pointer to your current location in the list (this avoids the O(N) cost of each pop(0) call).

    Python 3:

        def levelOrder(self,root):
            q = []
            if root is not None:
                q.append(root)
            i = 0
            while i < len(q):
                n = q[i]
                if n.left is not None:
                    q.append(n.left)
                if n.right is not None:
                    q.append(n.right)
                i += 1
            print(" ".join(str(x.data) for x in q))