给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list1 = new ArrayList<List<Integer>>();
if(root == null){
return list1;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
TreeNode temp = new TreeNode();
while(!queue.isEmpty()){
List<Integer> list2 = new ArrayList<Integer>();
int size = queue.size();
for(int i = 0;i < size;i++){
temp = queue.poll();
list2.add(temp.val);
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
}
list1.add(list2);
}
return list1;
}
}