Thursday, June 12, 2014

LeetCode (Python): 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).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

Solution:

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

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def levelOrder(self, root):
        solution=[]
        if root == None:
            return solution
        levelToProcess =[root]
        while len(levelToProcess)>0:
            numbersLevel =[]
            nextLevel = []
            for temp in levelToProcess:
                numbersLevel.append(temp.val)
                if temp.left != None:
                    nextLevel.append(temp.left)
                if temp.right != None:
                    nextLevel.append(temp.right)
            solution.append(numbersLevel)
            levelToProcess = nextLevel
        return solution

2 comments :

  1. wrong answer. You should reverse the solution list

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete