【问题描述】
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] ]
【思路】
递归实现
维护一个Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
层次扫描节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {
return result;
}
//创建一个队列,用于存放所有节点
Queue<TreeNode> currentLevel = new LinkedList<TreeNode>();
currentLevel.add(root);
while(!currentLevel.isEmpty()){
//创建List记录当前层节点值
List<Integer> currentList = new LinkedList<Integer>();
int size = currentLevel.size();
for (int i = 0; i < size; i++) {
TreeNode currentNode = currentLevel.poll();
currentList.add(currentNode.val);
if (currentNode.left != null) {
currentLevel.add(currentNode.left);
}
if (currentNode.right != null) {
currentLevel.add(currentNode.right);
}
}
result.add(currentList);
}
return result;
}
}