Tree (traversal)

Please help what is wrong with my codes? I created Tree.cpp. main.cpp and Node.h, Tree.h. It gives me an error.

//Tree.cpp
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
  #include "Tree.h"

Tree::Tree()
{
    root = NULL;
}
//INORDER
void Tree::inorder(Node* p)
{
    if(p!=NULL)
    {
        inorder(p->left);
        cout << " " << p->data<< " ";
        inorder(p->right);
    }
}
//PREORDER
void Tree::preorder(Node* p)
{
    if(p!=NULL)
    {
        cout << " " << p->data<< " ";
        preorder(p->left);
        preorder(p->right);
    }
}
//POSTORDER
void Tree::postorder(Node* p)
{
    if(p!=NULL)
    {
        postorder(p->left);
        postorder(p->right);
        cout << " " << p->data << " ";
    }
}


//main.cpp
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
#include <iostream>
#include "Node.h"
#include "Tree.h"
using namespace std;

int main()
{
    Tree tree;


    tree.root = new Node;

    tree.root->data=1;

    tree.root->left= new Node;
    tree.root->left->data=2;

    tree.root->right=new Node;
    tree.root->right->data=3;

    tree.root->left->left=new Node;
    tree.root->left->left->data=4;

    tree.root->left->right=new Node;
    tree.root->left->right->data=5;

    //Traversals
    cout << "INORDER:";
    tree.inorder(tree.root);
    cout << "\nPREORDER:";
    tree.preorder(tree.root);
    cout << "\nPOSTORDER:";
    tree.postorder(tree.root);

    return 0;
}


//Node.h
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef NODE_H
#define NODE_H

class Node{
public:
    int data;
    Node* left;
    Node* right;

};

#endif // NODE_H 


//Tree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TREE_H
#define TREE_H


class Tree{
public:
    Tree();
    Node* root;
    void inorder(Node*);
    void preorder(Node*);
    void postorder(Node*);
};
#endif // TREE_H
At a cursory glance, Tree.h needs to declare the type Node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef TREE_H
#define TREE_H

class Node ;

class Tree{
public:
    Tree();
    Node* root;
    void inorder(Node*);
    void preorder(Node*);
    void postorder(Node*);
};
#endif // TREE_H 


And Tree.cpp needs to #include Node.h
Last edited on
Topic archived. No new replies allowed.