HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Creating a list of list after traversing binary search tree in level order

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
afterordersearchcreatingleveltraversingbinarylisttree

Problem

Here is my code.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
 public List> levelOrder(TreeNode root) {
        List> list = new LinkedList>();
        if (root == null) {
            return list;
        } else {
            Queue q = new LinkedList<>();
            q.add(root);
            while (!q.isEmpty()) {
                int size = q.size();
                LinkedList layers = new LinkedList<>();
                while (size != 0) {
                    TreeNode current = q.poll();
                    layers.add(current.val);
                    if (current.left != null) {
                        q.add(current.left);
                    }
                    if (current.right != null) {
                        q.add(current.right);
                    }
                    size--;
                }

                list.add(layers);

            }
        }
        return list;

    }

}


Please let me know if any improvement/correction.

Solution

Nicely done. I especially like how you used the size of the queue to know how many items are there on the level. I have only minor improvement ideas.

You can simplify this declaration:

List> list = new LinkedList>();


Using the diamond operator <>, like you already did at other places:

List> list = new LinkedList<>();


The code is deeply indented. You could reduce the indent level by eliminating the else branch of the outermost condition:

if (root == null) {
        return list;
    }
    Queue q = new LinkedList<>();
    q.add(root);
    // ...


The while loop could be written as a for loop. The benefit is that it will be harder to forget to decrement size.

Lastly, some of the names could be better.

  • Instead of "layers", I propose singular "layer"



  • Instead of "size", I propose "count"

Code Snippets

List<List<Integer>> list = new LinkedList<List<Integer>>();
List<List<Integer>> list = new LinkedList<>();
if (root == null) {
        return list;
    }
    Queue<TreeNode> q = new LinkedList<>();
    q.add(root);
    // ...

Context

StackExchange Code Review Q#120119, answer score: 4

Revisions (0)

No revisions yet.