|
| 1 | +class Solution(): |
| 2 | + def levelOrder(self, root): |
| 3 | + ret = [] |
| 4 | + level = [root] |
| 5 | + while root and level: |
| 6 | + currentNodes = [] |
| 7 | + nextLevel = [] |
| 8 | + for node in level: |
| 9 | + currentNodes.append(node.val) |
| 10 | + if node.left: |
| 11 | + nextLevel.append(node.left) |
| 12 | + if node.right: |
| 13 | + nextLevel.append(node.right) |
| 14 | + ret.append(currentNodes) |
| 15 | + level = nextLevel |
| 16 | + return ret |
| 17 | + |
| 18 | + |
| 19 | +# Definition for a binary tree node. |
| 20 | +# class TreeNode(object): |
| 21 | +# def __init__(self, x): |
| 22 | +# self.val = x |
| 23 | +# self.left = None |
| 24 | +# self.right = None |
| 25 | + |
| 26 | +class Solution(object): |
| 27 | + def levelOrder(self, root): |
| 28 | + """ |
| 29 | + :type root: TreeNode |
| 30 | + :rtype: List[List[int]] |
| 31 | + """ |
| 32 | + if not root: |
| 33 | + return [] |
| 34 | + queue, result = [root], [[root.val]] |
| 35 | + |
| 36 | + while queue: |
| 37 | + queue_new = queue |
| 38 | + queue = [] |
| 39 | + result_temp = [] |
| 40 | + for current in queue_new: |
| 41 | + # current = queue_new.pop() |
| 42 | + if current.left: |
| 43 | + queue.append(current.left) |
| 44 | + result_temp.append(current.left.val) |
| 45 | + if current.right: |
| 46 | + queue.append(current.right) |
| 47 | + result_temp.append(current.right.val) |
| 48 | + if len(result_temp)>0: |
| 49 | + result.append(result_temp) |
| 50 | + |
| 51 | + return result |
0 commit comments