leetcode OJ java Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
/ \
9  20
/  \
15   7


return its level order traversal as:

[
[3],
[9,20],
[15,7]
]


import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class isBalanced {

public static List<List<Integer>> levelOrder(TreeNode root){
Queue <TreeNode> que = new LinkedList<TreeNode>();
List<List<Integer>> re = new ArrayList<List<Integer>>();
List<Integer> ro = new ArrayList<Integer>();
TreeNode tmp = root;
if(tmp == null) {
return re;
}
que.offer(tmp);
while(!que.isEmpty()){
Queue <TreeNode> que1 = new LinkedList<TreeNode>();
while(!que.isEmpty()){
tmp = que.peek();
que.poll();
if(tmp.left != null)
que1.offer(tmp.left);
if(tmp.right != null)
que1.offer(tmp.right);
}
List<Integer> roo = new ArrayList<Integer>(ro);
ro.clear();
que = que1;
}

return re;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode(3);
TreeNode rl = new TreeNode(9);
TreeNode rr = new TreeNode(20);
TreeNode rrl = new TreeNode(15);
TreeNode rrr = new TreeNode(7);
root.left = rl;
root.right = rr;
rr.left = rrl;
rr.right = rrr;
List<List<Integer>>  a = levelOrder(root);
System.out.println(a);

}

}

1、 用ctrl + shift + o 自动导入包的时候LIST包的选择有误，应该选util的

2、之前不熟悉java中队列对应的方法，常用的方法有：

poll() 实现了pop 操作

peak() 则是取出队列中的第一个元素。

3、最初的时候并没有引入 roo  ，得到的结果是全空。 我认为可能是ro 分配的时候指向了一个地址，clear()之后re中ro指向的地方被clear掉了。 因此引入了roo 。

具体的原因求大神解释，之前用到list的时候出现过很多次这样的情况。

LeetCode 107:Binary Tree Level Order Traversal II

2015-05-31 00:11:23

Binary Tree Zigzag Level Order Traversal -- LeetCode

2014-04-26 04:31:29

leetcode 102 Binary Tree Level Order Traversal

2015-07-14 22:53:54

LeetCode102 Binary Tree Level Order Traversal Java

2016-04-23 14:20:55

【LeetCode】102. Binary Tree Level Order Traversal 解题报告

2016-05-26 15:06:54

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

2015-09-11 02:20:37

leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)

2014-03-28 20:28:01

LeetCode --- 107. Binary Tree Level Order Traversal II

2015-04-17 16:46:33

【LeetCode】107. Binary Tree Level Order Traversal II 解题报告

2016-05-26 16:18:51

leetcode 107 Binary Tree Level Order Traversal II C++

2016-05-28 20:57:50

不良信息举报

leetcode OJ java Binary Tree Level Order Traversal