queue = [root] res = [] while queue: res.append([node.val for node in queue]) nqueue = [] for node in queue: if node.left: nqueue.append(node.left) if node.right: nqueue.append(node.right) queue = nqueue return res
classSolution(object): deflevelOrderBottom(self, root): ifnot root: return [] queue = [root] res = [] while queue: res.append([node.val for node in queue]) nqueue = [] for node in queue: if node.left: nqueue.append(node.left) if node.right: nqueue.append(node.right) queue = nqueue return res[::-1]
classSolution(object): defaverageOfLevels(self, root): ifnot root: return [] res = [] queue = [root] while queue: level = [node.val for node in queue] ret = 1.0 * sum(level) / len(level) res.append(ret) nqueue = [] for node in queue: if node.left: nqueue.append(node.left) if node.right: nqueue.append(node.right) queue = nqueue return res
queue = [root] res = [] while queue: level = [node.val for node in queue] if len(res) % 2: level.reverse() res.append(level) nqueue = [] for node in queue: if node.left: nqueue.append(node.left) if node.right: nqueue.append(node.right) queue = nqueue return res
Another Solution : Use Deque! In the even level:expand a node from the right end of the dequ, generate right and then left child, and insert them to the left end of the deque.
queue = [(root, 0)] res = 1 while queue: nqueue = [] for node, idx in queue: if node.left: nqueue.append((node.left, 2*idx)) if node.right: nqueue.append((node.right, 2*idx+1)) if nqueue: res = max(res, nqueue[-1][1] - nqueue[0][1] + 1) queue = nqueue return res