Game development as an Art

Sato Game Dev

Code Exercises


Tree preorder Traversal


Source: Hacker rank

Complete the preOrder function in your 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 hidden tester code passes the root node of a binary tree to your preOrder function.

Constraints

Nodes in the tree

Output Format

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

Sample Input


Sample Output

1 2 5 3 4 6

My solution:
C#:

Class Program:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TreePreorderTraversal
{
    class Program
    {

        public static void preOrder(Node root)
        {
            if (root == null)
                return;

            //visiting node
            Console.WriteLine(root.data);

            //going left node
            preOrder(root.left);
            //going right node
            preOrder(root.right);
        }

        public static Node insert(Node root, int data)
        {
            if (root == null)
            {
                return new Node(data);
            }
            else
            {
                Node cur;
                if (data <= root.data)
                {
                    cur = insert(root.left, data);
                    root.left = cur;
                }
                else
                {
                    cur = insert(root.right, data);
                    root.right = cur;
                }
                return root;
            }
        }

        static void Main(string[] args)
        {

            int t = Convert.ToInt32(Console.ReadLine());
            Node root = null;
            while (t-- > 0)
            {
                int data = Convert.ToInt32(Console.ReadLine());
                root = insert(root, data);
            }
            Console.WriteLine("\nOutput:");
            preOrder(root);
            Console.ReadKey();
        }
    }
}

Node class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TreePreorderTraversal
{
    class Node
    {
        public int data;
        public Node left;
        public Node right;

        public Node (int data)
        {
            this.data = data;
        }

    }
}