Python solution using a list as a queue (BFS)


  • 0
    L

    class Solution:
    def levelOrder(self, root):
    """
    :type root: TreeNode
    :rtype: List[List[int]]
    """
    if root==None: return []
    q=[root]
    ans=[]
    while q!=[]:
    current_l=len(q)
    level=[]
    for i in range(current_l):
    if q[i].left!=None:
    q.append(q[i].left)
    if q[i].right!=None:
    q.append(q[i].right)
    for i in range(current_l):
    level.append(q.pop(0).val)
    ans.append(level)
    return ans


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.