Binary Tree Level Order Traversal II

Problem: Binary Tree Level Order Traversal II

Just add each level to head of array.

Code in Python:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root: return []
        res = []
        level = [root]
        while level:
            current, next = [], []
            for node in level:
                current.append(node.val)
                if node.left: next.append(node.left)
                if node.right: next.append(node.right)
            res = [current] + res
            level = next
        return res

results matching ""

    No results matching ""