Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given the root
of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
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>> levelOrder(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(subList);
}
return wrapList;
}
}
vector<vector<int>> ret;
void buildVector(TreeNode *root, int depth)
{
if(root == NULL) return;
if(ret.size() == depth)
ret.push_back(vector<int>());
ret[depth].push_back(root->val);
buildVector(root->left, depth + 1);
buildVector(root->right, depth + 1);
}
vector<vector<int> > levelOrder(TreeNode *root) {
buildVector(root, 0);
return ret;
}
def levelOrder(self, root):
ans, level = [], [root]
while root and level:
ans.append([node.val for node in level])
LRpair = [(node.left, node.right) for node in level]
level = [leaf for LR in LRpair for leaf in LR if leaf]
return ans
In our experience, we suggest you solve this Binary Tree Level Order Traversal 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 LeetCode Solution
I hope this Binary Tree Level Order Traversal 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 >>