Created
May 3, 2018 23:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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