Give a pointerbased representation C declaration for a tree

Give a pointer-based representation (C++ declaration) for a tree with the root r Except the constructor and its implementation, you do not need to include other methods. Based on 1, for the following tree, give the representation for root r and vertices u and v.

Solution

             Pointer to Left Node , Pointer to Right Node and Data (Int/Foloat/String)

      2. In our Programme we made a Class called \"TreeNode\"

           It have 3 private members

                    Pointer to Left Node , Pointer to Right Node and String Data \"Char*\"

     3. We initilaized Pointer to Left/ Pointer to Right and Data (char *) in constructore

         We can right seperate methods to set Pointer to Left/ Pointer to Right and Data

   4.Please read comments in code

TreeNode.h (header file)

-------------------------------------------------

#ifndef TREENODE_H
#define TREENODE_H
#include <stdio.h>
#include <string.h>

class TreeNode
{
private:
    TreeNode* right;//Pointer to Right node
    TreeNode* left;//Pointer to Left node
    char* addr; // Data, String \"a\"/\"b\"/\"c\" , You can change as per your need like Int/Double..

public:
    TreeNode(TreeNode* left,TreeNode* right,char* data);
};

#endif // TREENODE_H

TreeNode.cpp (source file)

-------------------------------------------------

#include \"treenode.h\"
#include <stdlib.h>
TreeNode::TreeNode(TreeNode* left,TreeNode* right,char* data)
{
    this->left = left;
    this->right = right;
    //Allocate Memory for Data
    this->addr = (char*)malloc(strlen(data));
    //Copy String given in parameter to Node Object Data
    memcpy(this->addr,data,strlen(data));


}


Main file :-

---------------------------

#include <iostream>
#include <treenode.h>
using namespace std;

int main(int argc, char *argv[])
{
    //Create \"V\" Node with Straing \"e\"
    char * data = \"e\";
    // Node have Left and Right Child NULL becuase it has no children
    TreeNode V(NULL,NULL,data);

    //Create \"U\" Node with Straing \"b\"
     data = \"b\";
    // Node have Left child as \"V\" and Right Child as NULL becuase it has no right child
    TreeNode U(&V,NULL,data);

    //Create \"R\" Node with Straing \"b\"
     data = \"a\";
    // Node have Left child as \"U\" and Right Child as NULL becuase it has no right child
    TreeNode R(&U,NULL,data);

    return 0;
}

                   

 Give a pointer-based representation (C++ declaration) for a tree with the root r Except the constructor and its implementation, you do not need to include othe
 Give a pointer-based representation (C++ declaration) for a tree with the root r Except the constructor and its implementation, you do not need to include othe

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site