102. Binary Tree Level Order Traversal - LeetCode Solution


Tree

Python Code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return 
        
        q = []
        
        ans = []
        q.append(root)
        q.append(None)
        s = []
        
        count = 0
        
        while len(q)!= 0:
            root = q.pop(0)
            
            
            if root==None:
                count+=1
                if count==2:
                    break
                ans.append(s)
                s = []
                q.append(None)
                continue
                
            else:

                count = 0 

                s.append(root.val)

                if root.left:
                    q.append(root.left)


                if root.right:
                    q.append(root.right)
            

        return ans
            
            
            


Comments

Submit
0 Comments
More Questions

Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game