从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<IList<int>> LevelOrder(TreeNode root) {
List<IList<int>> list=new List<IList<int>>();
if(root==null)
{
return list;
}
Queue<TreeNode> queue=new Queue<TreeNode>();
queue.Enqueue(root);
while(queue.Count>0)
{
List<int> level=new List<int>();
for(int cut=queue.Count; cut>0; cut--)
{
var cur=queue.Dequeue();
level.Add(cur.val);
if(cur.left!=null)
{
queue.Enqueue(cur.left);
}
if(cur.right!=null)
{
queue.Enqueue(cur.right);
}
}
list.Add(level);
}
return list;
}
}