您的位置:首页 > 其它

69 - 二叉树的层次遍历

2017-03-31 19:54 363 查看
3.31
当把一个对象的值,赋给另外一个对象的时候,只是赋值地址。也就是说,二者是指向同一片内存区域的。

如果要创建两个不同的对象,可以使用clone这个函数。

在这个问题上确实困扰了很久

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
//用来存放最后的结果
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
//队列 用来遍历
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
//用来存放每一层的结果
ArrayList<Integer> tmp = new ArrayList<Integer>();
if(root == null){
return list;
}
queue.addLast(root);
TreeNode bt = root;
TreeNode flag = root;
//list.add(null);
//System.out.print(list.size());
while(!queue.isEmpty()){
bt = queue.pop();
tmp.add(bt.val);
if(bt.left != null){
queue.addLast(bt.left);
}
if(bt.right != null){
queue.addLast(bt.right);
}
if(!queue.isEmpty() && bt ==flag){
// 不可以直接使用这种形式 add = tmp;因为会指向同一片内存,然后tmp.clear就为空了。
ArrayList<Integer> add = (ArrayList<Integer>)tmp.clone();
list.add(add);
//add = (ArrayList<Integer>)tmp.clone();
tmp.clear();
flag = queue.getLast();
}
}
list.add(tmp);

return list;// write your code here
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: