Easy Java solution


  • 0
    Z

    public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> rst = new ArrayList<List<Integer>>();
    helper(root, rst, 0);
    return rst;
    }

    public void helper(TreeNode root, List<List<Integer>> rst,int level){
        if(root == null){
            return;
        }
        if(rst.size() - 1 < level){
            List<Integer> sol = new ArrayList<Integer>();
            sol.add(root.val);
            rst.add(new ArrayList<Integer>(sol));
            helper(root.left, rst, level+1);
            helper(root.right, rst, level+1);
        }
        else{
            rst.get(level).add(root.val);
            helper(root.left, rst, level+1);
            helper(root.right, rst, level+1);
        }
        return;
    }
    

    }


  • 0
    S

    @zhijianguo930608

    Very good. :) The next step would be to refactor your code. That will be a good exercise.

    There are places where you are repeating operations. Try to identify those lines and refactor that code.

    Finally, for this line rst.add(new ArrayList<Integer>(sol)); you can just change it to ```rst.add(sol);``


  • 0
    Z

    @some_name Hi, thank u for ur reply, and yes u r right, i always feel confused to figured it out whether it is a new List, or a list that already exist.


  • 0
    S

    @zhijianguo930608

    You're welcome. May I ask you why you get confused? Maybe I can help clarify things.


  • 0
    Z

    hey, i have already understand the issue.
    because in some cases
    like:
    List<List<Integer>> rst = new ArrayList<List<integer>>();
    List<Integer> ans = new ArrayList<integer>();
    in the first time ans = [1,2,3,4]
    rst.add(ans);
    int the second time ans = [1,2,3,4,5]
    rst.add(ans);
    I need to add both of them in the the rst
    without rst.add(new ArrayList<Integer>(ans)) for each time
    the second result will overwrite the first, and there will only be one list

    anyway I have already figured it out.


Log in to reply
 

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