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,null,null,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.LinkedList;
import java.util.List;
import java.util.Queue;
//Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<List<Integer>>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
q.add(root);
while(q.size()>0){
int size = q.size();
List<Integer> interlist = new ArrayList<Integer>();
for(int i=0; i<size; i++){
TreeNode front = q.poll();
interlist.add(front.val);
if(front.left != null){
q.add(front.left);
}
if(front.right != null){
q.add(front.right);
}
}
list.add(interlist);
}
return list;
}
public static void main(String[] args) {
}
}
树的层次遍历:每次遍历一层元素放入队列中,然后遍历队列中的所有元素,将元素的左右子节点都依次放入队列中,循环直至队列为空。
例:[3,9,20,null,null,15,7]
3 -> queue
remove 3 9,20->queue
remove 9, remove 20, 15,7->queue