给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
/**
* 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) {
if( root == null) return new ArrayList<>();
Queue<TreeNode> que = new LinkedList<TreeNode>();
List<List<Integer>> out = new ArrayList<>();
que.add(root);
while(que.size() != 0){
List<Integer> temp = new ArrayList<>();
Queue<TreeNode> que1 = new LinkedList<TreeNode>();
while(que.size() != 0){
TreeNode fz = que.poll();
temp.add(fz.val);
if(fz.left != null) que1.add(fz.left);
if(fz.right != null) que1.add(fz.right);
}
que = que1;
out.add(temp);
}
return out;
}
}