Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

print the top view of the binary tree

void TopView(Node root)
{
    Queue q = new Queue();
    SortedDictionary<int, Node> topViewMap
      = new SortedDictionary<int, Node>();

    if (root == null) {
      return;
    }
    else {
      q.Enqueue(new QueueObj(root, 0));
    }

    // count function returns 1 if the container
    // contains an element whose key is equivalent
    // to hd, or returns zero otherwise.
    while (q.Count != 0) {
      QueueObj tmpNode = (QueueObj)q.Dequeue();

      if (!topViewMap.ContainsKey(tmpNode.hd)) {
        topViewMap[tmpNode.hd] = tmpNode.node;
      }

      if (tmpNode.node.left != null) {
        q.Enqueue(new QueueObj(tmpNode.node.left,
                               tmpNode.hd - 1));
      }
      if (tmpNode.node.right != null) {
        q.Enqueue(new QueueObj(tmpNode.node.right,
                               tmpNode.hd + 1));
      }
    }

    foreach(var entry in topViewMap.Values)
    {
      Console.Write(entry.data);
    }
}
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #print #top #view #binary #tree
ADD COMMENT
Topic
Name
2+6 =