online advertising

Sunday, November 27, 2016

HackerRank - Tree: Preorder Traversal

Problem:

Please find the problem here.

Solution: 

We will have a series of HackerRank problem related to trees. Some of the problems (like this one) is just too simple so we will skip the analysis or even solution in this case. Frankly, this is really just the definition of pre-order traversal, nothing interesting to talk about.

I am doing this just to keep my habit straight - one problem - one blog post. The principle is that a problem is not completed without a blog post, and there is a reason for it. Some problems involves good thinking, and if I don't document it in time, the idea just goes away, leaving the rather useless code that I have to reverse engineer the thought. Sometimes I can, sometimes I can't, and why risk?

Code:

#include "stdafx.h"

// https://www.hackerrank.com/challenges/tree-preorder-traversal

#include "HACKER_RANK_TREE_PREORDER_TRAVERSAL.h"
#include <map>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

namespace _HACKER_RANK_TREE_PREORDER_TRAVERSAL
{
    struct node
    {
        int data;
        node* left;
        node* right;
    };

    void preOrder(node *root)
    {
        if (root == nullptr)
        {
            return;
        }
        cout << root->data << " ";
        preOrder(root->left);
        preOrder(root->right);
    }
};

using namespace _HACKER_RANK_TREE_PREORDER_TRAVERSAL;

int HACKER_RANK_TREE_PREORDER_TRAVERSAL()
{
    node a;
    node b;
    node c;
    node d;
    node e;
    node f;
    a.data = 3;
    b.data = 5;
    c.data = 2;
    d.data = 1;
    e.data = 4;
    f.data = 6;
    a.left = &b;
    a.right = &c;
    b.left = &d;
    b.right = &e;
    c.left = &f;
    c.right = nullptr;
    d.left = nullptr;
    d.right = nullptr;
    e.left = nullptr;
    e.right = nullptr;
    f.left = nullptr;
    f.right = nullptr;
    preOrder(&a);
    return 0;
}

No comments :

Post a Comment