Instagram
youtube
Facebook
Twitter

Preorder Traversal| Tree

Task(easy)

Complete the PreOrder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values.

Input Format
Our test code passes the root node of a binary tree to the preOrder function.


Constraints
 

1 Nodes in the tree ≤ 500


Output Format
Print the tree's preorder traversal as a single line of space-separated values.

Sample Input

 

1
\
2
\

5
/\
3  6

\

4

Sample Output

2  5  3  6  4

SOLUTION 1

def preOrder(root):

    #Write your code here

    cur = root

    if cur:

        print(cur.info, end=' ')

        if cur.left:

            preOrder(cur.left)          

        if cur.right:

            preOrder(cur.right)

    return

SOLUTION 2

def preOrder(root):

    result = []

     def traverse(node):

        if not node:

            return

        result.append(str(node.info))

        traverse(node.left)

        traverse(node.right)

    traverse(root)

    print(" ".join(result))