102.Binary Tree Level Order Traversal

Tags: [queue], [tree], [binary_tree], [BFS], [level_by_level]

Com: {fb}

Link: https://leetcode.com/problems/binary-tree-level-order-traversal/\#/description

Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Solution: Queue

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

from collections import deque

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []

        result = []
        buff = []
        queue = deque([root, None])
        while queue:
            curr = queue.popleft()
            if curr:
                buff.append(curr.val)
                if curr.left:
                    queue.append(curr.left)
                if curr.right:
                    queue.append(curr.right)
            else:
                if buff:
                    result.append(list(buff))
                    buff = []

                if queue:
                    queue.append(None)

        return result

Note:

  • Time complexity = O(n), n is the number of nodes of the given tree.
  • Time complexity = O(n), n is the number of nodes of the given tree.

results matching ""

    No results matching ""