LeetCode 102 Binary Tree Level Order Traversal

LeetCode 102 Binary Tree Level Order Traversal Problem

Download Code
# 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 levelOrder(self, root):
    #     """
    #     :type root: TreeNode
    #     :rtype: List[List[int]]
    #     """
    #     res = []
    #     if root is None:
    #         return []
    #     self.get_level(res, root, 0)
    #     return res
    #
    # def get_level(self, res, root, depth):
    #     if root is None:
    #         return
    #     if depth == len(res):
    #         res.append([])
    #     res[depth].append(root.val)
    #     self.get_level(res, root.left, depth + 1)
    #     self.get_level(res, root.right, depth + 1)

    def levelOrder(self, root):
        # https://leetcode.com/discuss/90680/9-lines-python-code
        if root is None:
            return []
        q = [[root]]
        for level in q:
            record = []
            for node in level:
                if node.left:
                    record.append(node.left)
                if node.right:
                    record.append(node.right)
            if record:
                q.append(record)
        return [[x.val for x in level] for level in q]

Download Binary Tree Level Order Traversal.py

List of all Binary Tree Level Order Traversal problems

Leetcode 102 Binary Tree Level Order Traversal problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

self.val = x

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.