69 - 二叉树的层次遍历
2017-03-31 19:54
363 查看
3.31
当把一个对象的值,赋给另外一个对象的时候,只是赋值地址。也就是说,二者是指向同一片内存区域的。
如果要创建两个不同的对象,可以使用clone这个函数。
在这个问题上确实困扰了很久
当把一个对象的值,赋给另外一个对象的时候,只是赋值地址。也就是说,二者是指向同一片内存区域的。
如果要创建两个不同的对象,可以使用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 } }
相关文章推荐
- 69.二叉树的层次遍历
- 【LintCode 简单】69. 二叉树的层次遍历
- LintCode【简单】69. 二叉树的层次遍历。代码及思路
- LintCode-69.二叉树的层次遍历
- LintCode | 69. 二叉树的层次遍历
- 【LintCode-69】二叉树的层次遍历(Java实现)
- lintcode-二叉树的层次遍历-69
- LintCode 69 二叉树的层次遍历
- lintcode 69. 二叉树的层次遍历
- LintCode-剑指Offer-(69)二叉树的层次遍历
- [LintCode 69] 二叉树的层次遍历 (Python)
- LintCode 69-二叉树的层次遍历
- python_lintcode_69二叉树的层次遍历
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树-建树,层次遍历,先序遍历,中序遍历,后序遍历
- 第十周项目2二叉树的层次遍历算法
- 二叉树第K层的第M个节点 -- 采用非递归层次遍历实现
- 二叉树之层次遍历
- leet102. 二叉树的层次遍历
- 分层次遍历二叉树