You are given a pointer to the root of a binary tree. Print the top view of the binary tree.
Top view means when you look the tree from the top the nodes you will see will be called the top view of the tree. See the example below.
You only have to complete the function.
For example :

   1
    \
     2
      \
       5
      /  \
     3    6
      \
       4

Top View : 1 -> 2 -> 5 -> 6

Input Format

You are given a function,

void topView(node * root) {

}

Constraints

1Nodes in the tree500

Output Format

Print the values on a single line separated by space.

Sample Input

1.   1
      \
       2
        \
         5
        /  \
       3    6
        \
         4


2.    1
     / \
    2   3
   / \
  4   5
       \
        6
         \
          7

Sample Output

1 2 5 6

4 2 1 3


Code:(Accepted but not optimal)

"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)"""

def topView(root):
    result = []
    stack = []
    if root.left:
        currentNode = root.left
        while currentNode!= None:
            stack.append(currentNode.data)
            currentNode = currentNode.left

    while stack:
        result.append(stack.pop())
    result.append(root.data)
    if root.right:
        currentNode = root.right
        while currentNode!= None:
            result.append(currentNode.data)
            currentNode = currentNode.right

    #if root.left:
    for i in result:
        print i,

results matching ""

    No results matching ""