卖萌的弱渣

I am stupid, I am hungry.

Binary Tree Level Order Traversal

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

Example

Given binary tree {3,9,20,#,#,15,7},

1
2
3
4
5
    3
   / \
  9  20
    /  \
  15   7

return its level order traversal as:

1
2
3
4
5
[
  [3],
  [9,20],
  [15,7]
]

Challenge

Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use DFS algorithm to do it.

Solution

  • Time O(n)
  • Count the queue.size() in the beginging of iteration, that is the num of nodes in each level.
(Binary-Tree-Level-Order-Traversal.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: Level order in a list of lists of integers
    """
    def levelOrder(self, root):
        # write your code here
        q = []
        q.append(root)
        result = []
        if root == None:
            return result

        while len(q)!=0:
            # size = num of nodes in each level
            size = len(q)
            row = []
            for i in range(size):
                node = q.pop(0)
                row.append(node.val)

                if node.left != None:
                    q.append(node.left)
                if node.right != None:
                    q.append(node.right)
            result.append(row)

        return result