为什么我的方法打印一个空列表?

时间:2018-02-11 06:24:11

标签: java algorithm arraylist binary-tree

我正在尝试在dimensions: s_rho = 30; eta_rho = 116; xi_rho = 165; ocean_time = UNLIMITED; // (30 currently) variables: double lat_rho(eta_rho=116, xi_rho=165); :long_name = "latitude of RHO-points"; :units = "degree_north"; :standard_name = "latitude"; :field = "lat_rho, scalar"; :_CoordinateAxisType = "Lat"; double lon_rho(eta_rho=116, xi_rho=165); :long_name = "longitude of RHO-points"; :units = "degree_east"; :standard_name = "longitude"; :field = "lon_rho, scalar"; :_CoordinateAxisType = "Lon"; double ocean_time(ocean_time=30); :long_name = "averaged time since initialization"; :units = "seconds since 1990-01-01 00:00:00"; :calendar = "gregorian"; :field = "time, scalar, series"; :_CoordinateAxisType = "Time"; float temp(ocean_time=30, s_rho=30, eta_rho=116, xi_rho=165); :long_name = "time-averaged potential temperature"; :units = "Celsius"; :time = "ocean_time"; :coordinates = "lon_rho lat_rho s_rho ocean_time"; :field = "temperature, scalar, series"; :_FillValue = 1.0E37f; // float 中逐级打印树。 ArrayList<ArrayList<Integer>> result中的每个列表都被视为自己的级别。

示例:

result

出于某种原因,我不断回到空列表。这是我的代码:

         1                
        / \             
       2   3   
      / \ / \           
     4  5 6  7
==>  [1][2, 3][4, 5, 6, 7]

是我的temp.clear()对吗?我尝试将它放在不同的地方,但仍然是相同的结果。我知道我可以使用两个public ArrayList<ArrayList<Integer>> printLevelByLevel(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> temp = new ArrayList<Integer>(); if(root == null) return result; int levelCount = 0; Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); while(true){ levelCount = q.size(); if(levelCount == 0) break; while(levelCount > 0){ TreeNode curr = q.poll(); temp.add(curr.data); if(curr.left != null){ q.add(curr.left); } if(curr.right != null){ q.add(curr.right); } levelCount--; } // end of inner while result.add(temp); temp.clear(); } // end of outter while loop return result; } 执行此操作,但我希望能够使用一个Queues执行此操作。

感谢。

1 个答案:

答案 0 :(得分:1)

多次将ArrayList实例(由temp变量引用)添加到reuslt列表中是错误的,因为您的result将包含多个空列表(或,更准确地说,最后是对同一个空列表的多次引用。

您应该在每次迭代中创建一个新实例,而不是通过temp清除单个实例引用:

while(true){
    levelCount = q.size();
    if(levelCount == 0) break;
    ArrayList<Integer> temp = new ArrayList<Integer>();
    while(levelCount > 0){
        TreeNode curr = q.poll();
        temp.add(curr.data);
        if(curr.left != null){
            q.add(curr.left);
        }
        if(curr.right != null){
            q.add(curr.right);
        }
        levelCount--;
    } // end of inner while 
    result.add(temp);
}