
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its bottom-up level order traversal as:
1 2 3 4 5
|
[ [15,7], [9,20], [3] ]
|
- Use queue to do level traversal + deque.appendleft or list[ : : -1] to realize bottom-up
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
from collections import deque class : def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = deque() q = [] q.append(root) while(q): temp = [] l = len(q) for _ in range(l): cur = q.pop(0) temp.append(cur.val) if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) res.appendleft(temp) return res
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class : def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] q = [] q.append(root) while(q): temp = [] l = len(q) for _ in range(l): cur = q.pop(0) temp.append(cur.val) if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) res.append(temp) return res[::-1]
|
Time complexity is O(n)
- DFS + record level
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
class : def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: res = [] self.dfs(res, 0, root) return res def dfs(self, res, level, node): if not node: return else: if len(res) < (level + 1): res.insert(0, []) res[-(level+1)].append(node.val) self.dfs(res, level + 1, node.left) self.dfs(res, level + 1, node.right)
|
So time complexity is O(n^2)
近期评论