//--------------------------------------------------------------------- //------------- B F S + I T E R A T I V E ------------------- //--------------------------------------------------------------------- //BFS: Level-order Traversal, Queue public List<List<int>> LevelOrderTraversal(TreeNode root) { List<List<int>> result = new List<List<int>>(); Queue<TreeNode> queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count != 0) { //Initiate a List<int> container for each level. List<int> level = new List<int>(); //Store the static size as loop condition (this is a must because queue.Count is shrinking in each loop.) int size = queue.Count; for (int i = 0; i < size; i++) { //Dequeue each node root = queue.Dequeue(); //Save the node value level.Add(root.val); //And enqueue its child at the same time if (root.left != null) queue.Enqueue(root.left); if (root.right != null) queue.Enqueue(root.right); } //Save the level after dequeue all the node. result.Add(level); } return result; }