Python 3 (Level Order Traversal)


#1

class Solution:
# @param A : root node of tree
# @return a list of integers

def solve(self, A):
    q=[]
    q.append(A)
    q.append(None)
    level=0
    dic={}
    while(q):
        node=q.pop(0)
        if(node!=None):
            if(level in dic):
                dic[level].append(node.val)
            else:
                dic[level]=[node.val]
        if(node==None):
            if(q!=[]):
                q.append(None)
                level+=1
        else:
            if(node.left):
                q.append(node.left)
            if(node.right):
                q.append(node.right)
                
    arr=[]
    for i in dic:
        ele=dic[i]
        arr.append(ele[-1])
        
    return(arr)