Last active
October 11, 2022 21:51
-
-
Save djaquels/1d0b2f014ca82a9dd4b9077fc725f67b to your computer and use it in GitHub Desktop.
ColumnOrder 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
/* Given the following binary tree | |
6 | |
/ \ | |
3 4 | |
/ / \ | |
5 1 0 | |
\ / | |
2 8 | |
/ \ | |
9 7 | |
*/ | |
using System; | |
using System.Collections.Generic; | |
namespace ColumnOrder{ | |
class ColumnOrder { | |
public static void Main(string[] args){ | |
Node a = new Node(6); | |
Node b = new Node(3); | |
Node c = new Node(5); | |
Node d = new Node(2); | |
Node e = new Node(9); | |
Node f = new Node(7); | |
// | |
Node g = new Node(4); | |
Node h = new Node(1); | |
Node i = new Node(0); | |
Node j = new Node(8); | |
// 10 nodes | |
a.Left = b; | |
a.Right = g; | |
b.Left = c; | |
c.Right = d; | |
d.Left = e; | |
d.Right = f; | |
g.Left = h; | |
g.Right = i; | |
i.Left = j; | |
int[] nodes = getColumnOrder(a,10); | |
for(int idx = 0; idx < 10; idx++){ | |
Console.Write("{0}, ",nodes[idx]); | |
} | |
} | |
private static int[] getColumnOrder(Node root, int size){ | |
int[] result = new int[size]; | |
Queue<(Node,int)> auxQueue = new Queue<(Node,int)>(); | |
Dictionary<int,List<int>> columnsMap = new Dictionary<int,List<int>>(); | |
auxQueue.Enqueue((root,0)); | |
int idx = 0; | |
while(auxQueue.Count != 0 ){ | |
(Node node, int level) current = auxQueue.Dequeue(); | |
if (current.node is null){ | |
continue; | |
} | |
if (columnsMap.ContainsKey(current.level)){ | |
columnsMap[current.level].Add(current.node.Value); | |
}else{ | |
columnsMap[current.level] = new List<int>(); | |
columnsMap[current.level].Add(current.node.Value); | |
} | |
auxQueue.Enqueue((current.node.Left,current.level-1)); | |
auxQueue.Enqueue((current.node.Right,current.level+1)); | |
} | |
foreach(KeyValuePair<int,List<int>> column in columnsMap.OrderBy(x => x.Key) ){ | |
foreach(int num in column.Value){ | |
result[idx] = num; | |
idx++; | |
} | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: 5, 9, 3, 2, 6, 1, 7, 4, 8, 0