Home > AI > Data Structure > Tree >

leetcode-102-Binary Tree Level Order Traversal

Solution: Python

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return 
        
        q = [root]
        re = []
        
        while q:
            tmpLen = len(q)
            levelList = []
            for i in range(tmpLen):
                tmp = q.pop(0)
                levelList.append(tmp.val)
                
                if tmp.left:
                    q.append(tmp.left)
                if tmp.right:
                    q.append(tmp.right)
            re.append(levelList)
        return re

Leave a Reply