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
wrong answer. You should reverse the solution list
ReplyDeleteThis comment has been removed by the author.
ReplyDelete