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]]
class Solution(object): def levelOrder(self, root): if not root: return [] stack, ans = [root], [] while stack: temp, stack_new = [], [] for x in stack: temp.append(x.val) if x.left: stack_new.append(x.left) if x.right: stack_new.append(x.right) ans.append(temp) stack = stack_new return ans