Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/e92fb90f564e800e8d78e04d5937ec73 to your computer and use it in GitHub Desktop.
Save jianminchen/e92fb90f564e800e8d78e04d5937ec73 to your computer and use it in GitHub Desktop.
Leetcode 102 - binary tree level order print - write C# code based on one of Java implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryTreeLevelOrderTraversal
{
class Program
{
static void Main(string[] args)
{
}
// Definition for a binary tree node.
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
/// <summary>
/// May 3, 2018
/// I like to write a C# solution based on this blog:
/// https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33710/Java-queue-solution-beats-100
/// </summary>
public class Solution
{
public IList<IList<int>> LevelOrder(TreeNode root)
{
var nodes = new List<IList<int>>();
if (root == null)
{
return nodes;
}
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
while (queue.Count > 0)
{
int currentLevelSize = queue.Count;
var layerNodes = new List<int>();
int index = 0;
while (index < currentLevelSize)
{
var node = queue.Peek();
queue.Dequeue();
layerNodes.Add(node.val);
if (node.left != null)
{
queue.Enqueue(node.left);
}
// bug - not else if - logic checking
if (node.right != null)
{
queue.Enqueue(node.right);
}
index++;
}
nodes.Add(layerNodes);
}
return nodes;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment