Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given the root
of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
[0, 2000]
.-1000 <= Node.val <= 1000
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
if(root == null) return wrapList;
queue.offer(root);
while(!queue.isEmpty()){
int levelNum = queue.size();
List<Integer> subList = new LinkedList<Integer>();
for(int i=0; i<levelNum; i++) {
if(queue.peek().left != null) queue.offer(queue.peek().left);
if(queue.peek().right != null) queue.offer(queue.peek().right);
subList.add(queue.poll().val);
}
wrapList.add(0, subList);
}
return wrapList;
}
}
def levelOrderBottom1(self, root):
res = []
self.dfs(root, 0, res)
return res
def dfs(self, root, level, res):
if root:
if len(res) < level + 1:
res.insert(0, [])
res[-(level+1)].append(root.val)
self.dfs(root.left, level+1, res)
self.dfs(root.right, level+1, res)
void levelOrder(vector<vector<int>> &ans, TreeNode *node, int level) {
if (!node) return;
if (level >= ans.size())
ans.push_back({});
ans[level].push_back(node->val);
levelOrder(ans,node->left,level+1);
levelOrder(ans,node->right,level+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
levelOrder(ans,root,0);
reverse(ans.begin(),ans.end());
return ans;
}
In our experience, we suggest you solve this Binary Tree Level Order Traversal II LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Binary Tree Level Order Traversal II LeetCode Solution
I hope this Binary Tree Level Order Traversal II LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>