# Is there a better solution?

• I use a queue to iterate the tree, and a label named head to point to the first node of each level.
Nevertheless, I don't think the code is concise enough. Is there a better solution for this question?

``````public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if(root==null) return ret;
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
queue.offer(root);
List<Integer> level = null;
while(!queue.isEmpty())
{
TreeNode top = queue.poll();
{
level = new ArrayList<Integer>();
}
if(top.left!=null) queue.offer(top.left);
if(top.right!=null) queue.offer(top.right);
{
}
}
ret.remove(0);
return ret;
}
}``````

• By better if you mean elegant,then may be :/

``````class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
struct queue<TreeNode *>q;
struct TreeNode *temp=root;
vector<vector<int> > v1;
vector<int> v;
if(!root)                                            //if root is NULL return vector of vectors
return v1;
q.push(temp);                                        //we don't want an empty queue,do we?
long long ago;      //in a galaxy far far away
ago=0;
while(!q.empty())
{
ago=q.size();                                 //this is the tricky part done so that every thing gets pushed and popped
while(ago)                                    //our hero comes to play
{temp=q.front();                                //but ofcourse if tree is 1,#2,3 (let) then 2 should be printedfirst(root)
v.push_back(temp->val);                         //I wonder why they took vector of vectors,that explains less accuracy.
if(temp->left)
q.push(temp->left);                             //go left for the 1 ,mind you this is iterative, queue =2,1,
if(temp->right)
q.push(temp->right);                            //go right                queue2,1,3
q.pop();                                        //pop 2,queue=1,3 count=0 go up count 1 again!! ,queue front has 2(FIFO)
ago--;
}
v1.push_back(v);                                //vector of vectors :(
v.clear();                                     // but ofcourse we don't need extra memory
}

return v1;                                        //vector of vectors :(.
}
};

//Much love to Shangrila for closing questions /answers without explanation
``````

• My solution is as below. I also use a queue to iterate the tree. The main idea is that we can keep two pointers which point to the end of current level (curLevelEnd) and the end of the next level (nextLevelEnd) respectively. When we add a TreeNode to the queue, we just update nextLevelEnd to point to this node. When we reach the end of current level, nextLevelEnd is assigned to curLevelEnd.

``````vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int>> result;
if (!root) return result;
queue<TreeNode*> q;
q.push(root);
result.push_back(vector<int>());
TreeNode* curLevelEnd = root, *nextLevelEnd = NULL;
while (!q.empty())
{
TreeNode* tmp = q.front();
q.pop();
result[result.size() - 1].push_back(tmp->val);
if (tmp->left)
{
q.push(tmp->left);
nextLevelEnd = tmp->left;
}
if (tmp->right)
{
q.push(tmp->right);
nextLevelEnd = tmp->right;
}
if (tmp == curLevelEnd)
{
result.push_back(vector<int>());
curLevelEnd = nextLevelEnd;
}
}
if (result[result.size() - 1].size() == 0) result.pop_back();
return result;
}``````

• My answer is similar to @cjxxm. It is written in java.

``````public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {

if (root==null) return result;

int current_layer=0;

while(!node_queue.isEmpty()){
int layer=layer_queue.pollFirst();

if (layer>current_layer){
list.clear();
current_layer=layer;
}

TreeNode node = node_queue.pollFirst();

if (node.left!=null){
}
if (node.right!=null){
}
}
return result;
}
``````

}

• Maybe just a little bit less code in java:

``````public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
List<TreeNode> level = new ArrayList<>();
while(true){
if (level.isEmpty() || level.get(0) == null){
break;
}
List<TreeNode> nextLevel = new ArrayList<>();
List<Integer> currentLevel = new ArrayList<>();

for (TreeNode node : level){
}
level = nextLevel;
}
return result;
}``````

• ``````public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(root==null)
return result;
List<TreeNode> cur=new ArrayList<TreeNode>();
while(cur.size()!=0){
List<TreeNode> next=new ArrayList<TreeNode>();
for(TreeNode i:cur){
if(i.left!=null)
if(i.right!=null)
}
cur=next;
}
return result;
}
``````

• This is my iterative solution

• I use the null as the split between levels, here's my

``````public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
List<Integer> tmp;
TreeNode cur;
if (root == null) {
return ret;
}
while (!queue.isEmpty()) {
tmp = new ArrayList<Integer>();
for (cur = queue.remove(); cur != null; cur = queue.remove()) {
}
if (tmp.size() > 0) {
}
}
return ret;
}
}``````

• thank you. very nice and organized code.

• That's super clear solution without using queue. Thx so much!
I'm just thinking maybe we can add "if(root == null) return res;" into the second line. And also change the while into "while(!level.isEmpty())", which is a little bit clear and easy to understand.

• This post is deleted!

• Here is my recursive solution:

``````class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if (root == None):
return [];
else:
all_levels = [[root.val]]
left_levels = self.levelOrder(root.left)
right_levels = self.levelOrder(root.right)
m = min(len(left_levels), len(right_levels))
for i in range(m):
all_levels.append( left_levels[i] + right_levels[i])
if (len(left_levels)>m):
for j in range(m, len(left_levels)):
all_levels.append(left_levels[j])

if (len(right_levels)>m):
for k in range(m, len(right_levels)):
all_levels.append(right_levels[k])
return all_levels
``````

• I also use the NULL as the split between levels, here's my:

``````class Solution {
public:
std::vector<std::vector<int> > levelOrder(TreeNode *root) {
std::vector<std::vector<int> > result;
if (root == NULL)
return result;
std::deque<TreeNode *> wait_nodes;
wait_nodes.push_back(root);
wait_nodes.push_back(NULL);
std::vector<int> nodes_val;
while (wait_nodes.size() != 1) {
root = wait_nodes.front();
wait_nodes.pop_front();
while (root != NULL) {
nodes_val.push_back(root->val);
if (root->left != NULL)
wait_nodes.push_back(root->left);
if (root->right != NULL)
wait_nodes.push_back(root->right);
root = wait_nodes.front();
wait_nodes.pop_front();
}
result.push_back(nodes_val);
wait_nodes.push_back(NULL);
nodes_val.clear();
}
return result;
}
};``````

• Nothing new here, just a bit simpler.

``````class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
vector<TreeNode*> level(root != 0, root);

int i = 0, l = 0;

while(i < level.size()){

res.push_back( vector<int>() );

for(int n = level.size(); i < n; i++){
res[l].push_back( level[i]->val );

if( level[i]->left )
level.push_back( level[i]->left );

if( level[i]->right )
level.push_back( level[i]->right );
}
l++;
}
return res;
}
};``````

• wow! what a neat solution! Up stair's advice is great too.

• This post is deleted!

• a very naive BFS using two queues,one for every level and one for the whole loop.

``````class solution{public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q,l;
vector<vector<int>> ans;
if (root == NULL) return ans;
q.push(root);
l.push(root);
while (!q.empty())
{
vector<int> tmp;
while (!l.empty())
{
TreeNode* t = l.front();
l.pop();
q.pop();
tmp.push_back(t->val);
if (t->left != NULL)
q.push(t->left);
if (t->right != NULL)
q.push(t->right);
}
ans.push_back(tmp);
tmp.clear();
l = q;
}
return ans;
}}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.