题目:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
代码实现:
/**
* 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>> res = new ArrayList<>();
if(root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
recu(res, queue, 1);
return res;
}
private void recu(List<List<Integer>> res, Queue<TreeNode> queue, int num){
if(queue.isEmpty()){
return;
}
List<Integer> ceng = new ArrayList<>();
while(num-- > 0){
TreeNode node = queue.poll();
if(node == null){
continue;
}
ceng.add(node.val);
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
res.add(ceng);
recu(res, queue, queue.size());
return;
}
}