给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解答:
1.对于不为空的结点,先把该结点加入到队列中
2.从队中拿出结点,如果该结点的左右结点不为空,就分别把左右结点加入到队列中
3.重复以上操作直到队列为空
/**
* 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) {
List<List<Integer>> bb=new ArrayList<List<Integer>>();
LinkedList<TreeNode> queue =new LinkedList<TreeNode>();
TreeNode root1;
if (root == null) return bb;
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> aa=new ArrayList<Integer>();
int a=queue.size();
for (int i=0;i<a;i++)
{
root1 = queue.poll();
// printf("%c ", root -> data);
aa.add(root1.val);
if (root1.left!=null)
{
queue.add(root1.left);
}
if (root1.right!=null)
{
queue.add(root1.right);
}
}
bb.add(aa);
}
return bb;
}
}