Last active
July 7, 2016 02:57
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; | |
namespace ConsoleApplication1 | |
{ | |
class App | |
{ | |
public List<List<Item>> Nodes { get; set; } | |
public Item Head { get; set; } | |
public App() | |
{ | |
Nodes = new List<List<Item>>(); | |
InitializeData(); | |
} | |
public void Main() | |
{ | |
ProcessNode(Head, 0); | |
UpdateSiblings(); | |
DisplaySiblings(); | |
Console.ReadLine(); | |
} | |
private void DisplaySiblings() | |
{ | |
int level = 0; | |
foreach (var itemList in Nodes) | |
{ | |
level++; | |
Console.Write($"Level {level}:"); | |
Console.WriteLine(string.Join(",", itemList.Select(x => x.Id.ToString()).ToArray())); | |
DisplayLinkedListNode(itemList[0]); | |
Console.WriteLine(); | |
} | |
} | |
private void DisplayLinkedListNode(Item aItem) | |
{ | |
if(aItem != null) | |
{ | |
Console.Write($"{aItem.Id}"); | |
if (aItem.next != null) Console.Write(","); | |
DisplayLinkedListNode(aItem.next); | |
} | |
} | |
private void UpdateSiblings() | |
{ | |
foreach (var itemList in Nodes) | |
{ | |
Item currentItem = null; | |
foreach (var item in itemList) | |
{ | |
if (currentItem == null) | |
{ | |
currentItem = item; | |
} | |
else | |
{ | |
currentItem.next = item; | |
currentItem = item; | |
} | |
} | |
} | |
} | |
private void ProcessChildren(Item aItem, int aLevel) | |
{ | |
if (aItem != null) | |
{ | |
ProcessNode(aItem.Left, aLevel + 1); | |
ProcessNode(aItem.Right, aLevel + 1); | |
} | |
} | |
private void ProcessNode(Item aItem, int aLevel) | |
{ | |
if (aItem != null) | |
{ | |
EnsureItemList(aLevel); | |
Nodes[aLevel].Add(aItem); | |
ProcessChildren(aItem, aLevel); | |
} | |
} | |
private void EnsureItemList(int aLevel) | |
{ | |
if (Nodes.Count <= aLevel) | |
{ | |
Nodes.Add(new List<Item>()); | |
} | |
} | |
private void InitializeData() | |
{ | |
Head = new Item() | |
{ | |
Id = 1, | |
Left = new Item() | |
{ | |
Id = 2, | |
Left = new Item() | |
{ | |
Id = 3, | |
Left = null, | |
Right = new Item() | |
{ | |
Id = 4, | |
Left = null, | |
Right = null | |
} | |
}, | |
Right = new Item() | |
{ | |
Id = 5, | |
Left = null, | |
Right = null | |
} | |
}, | |
Right = new Item() | |
{ | |
Id = 6, | |
Left = null, | |
Right = null | |
} | |
}; | |
} | |
} | |
public class Item | |
{ | |
public int Id { get; set; } | |
public Item Left { get; set; } | |
public Item Right { get; set; } | |
public Item next { get; set; } | |
} | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
new App().Main(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment