I want to traverse a Binary Tree vertically. And I found a working code in Geeks for Geeks in C++. I want to convert it into C# but I am unable to do so. Please guide me.
Below is my attempt:
// we always need the address of the Root Node come what may!
public class BstNode
{
public int data { get; set; }
public BstNode left { get; set; }
public BstNode right { get; set; }
public BstNode(int value) => data = value;
}
public class BstTree
{
// For BST
public BstNode Insert(BstNode root, int data)
{
if (root == null)
{
root = new BstNode(data);
root.left = null;
root.right = null;
}
else if (data > root.data)
root.right = Insert(root.right, data);
else root.left = Insert(root.left, data);
return root;
}
// PROBLEM IN BELOW CODE
public void VerticalOrderTraverse(BstNode root)
{
// Base case
if (root == null)
return;
// Create a map and store vertical oder in
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
int hd = 0;
// Create queue to do level order traversal.
// Every item of queue contains node and
// horizontal distance.
Queue<Tuple<BstNode, int>> que = new Queue<Tuple<BstNode, int>>();
que.Enqueue(new Tuple<BstNode, int>(root, hd));
while (que.Count != 0)
{
// pop from queue front
Tuple<BstNode, int> temp = que.Peek();
que.Dequeue();
hd = temp.Item2;
BstNode node = temp.Item1;
// insert this node's data in vector of hash
dict.Add(hd, new List<int>(node.data)); // CONFUSED HERE
if (node.left != null)
que.Enqueue(new Tuple<BstNode, int>(node.left, hd - 1));
if (node.right != null)
que.Enqueue(new Tuple<BstNode, int>(node.right, hd + 1));
}
foreach (var item in dict)
foreach (var ite in item.Value)
Console.WriteLine(ite);
}
}
class Program
{
public static void Main()
{
BstNode root = null;
BstTree bstTree = new BstTree();
root = bstTree.Insert(root, 10);
root = bstTree.Insert(root, 12);
root = bstTree.Insert(root, 7);
root = bstTree.Insert(root, 8);
root = bstTree.Insert(root, 15);
root = bstTree.Insert(root, 11);
root = bstTree.Insert(root, 6);
bstTree.VerticalOrderTraverse(root);
}
}
Kindly note that I am getting exception in "VerticalOrderTraversal" Method. This VerticalOrderTraversal is exact replica of Vertical Order Traversal in C++
Exception: Key already exists in dictionary
EDIT:
After adding this check still the Logic does not give correct output
if (dict.ContainsKey(hd))
dict[hd].Add(node.data);
else dict.Add(hd, new List<int>(node.data));