107. Binary Tree Level Order Traversal II
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]
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import queue class Solution: def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: q = queue.Queue() if root: q.put(root) res = [] while q.qsize(): sz = q.qsize() cur = [] for i in range(sz): top = q.get() cur.append(top.val) if top and top.left: q.put(top.left) if top and top.right:q.put(top.right) res.append(cur) return res[::-1]
class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> res; if(root == nullptr) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { vector<int> single_res; int cnt = q.size(); for(int i = 0; i < cnt;++i) { root = q.front(); q.pop(); single_res.push_back(root->val); if(root->left != nullptr) q.push(root->left); if(root->right !=nullptr) q.push(root->right); } res.insert(res.begin(),single_res); } return res; } };
1 public class Solution { 2 public List<List<Integer>> levelOrderBottom(TreeNode root) { 3 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 4 List<List<Integer>> wrapList = new LinkedList<List<Integer>>(); 5 6 if(root == null) return wrapList; 7 8 queue.offer(root); 9 while(!queue.isEmpty()){ 10 int levelNum = queue.size(); 11 List<Integer> subList = new LinkedList<Integer>(); 12 for(int i=0; i<levelNum; i++) { 13 if(queue.peek().left != null) queue.offer(queue.peek().left); 14 if(queue.peek().right != null) queue.offer(queue.peek().right); 15 subList.add(queue.poll().val); 16 } 17 wrapList.add(0, subList); 18 } 19 return wrapList; 20 } 21 }