添加到二叉树C ++

时间:2017-04-07 02:40:05

标签: c++ data-structures binary-tree binary-search-tree

我需要帮助将节点插入二叉树。我的程序所做的是从.cpp和.h文件中读取有关棒球运动员的信息。此信息包含在二叉树的一个节点中。 当读入一个节点时,我需要使用insert函数来读取信息并对其进行相应的排序。我需要一些基本代码来帮助我完成这个过程。 到目前为止,我的插入函数有这个:

bool Tree::insert(Player player)
{
Node *pNew;
    Node *ROOT, *next;

    pNew = new Node(player);

    if(pNew == NULL)
    {
        return false;
    }

    ROOT = pRoot;
    next = NULL;

    while (ROOT != NULL && next -> item.lessThan(player))
    {
        ROOT = next;
        next = next -> pCurrent;

        if(next < ROOT)
        {

        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为使用递归函数更容易。这是一个很好的解释链接,可以更好地实现二叉树。 http://www.cprogramming.com/tutorial/lesson18.html基本上你想要使用二进制搜索遍历树,直到找到一个空的左或右指针。

 Bool Tree::insert(Player p1, node *leaf) //key is your player and leaf is parent node
{
  if(p1.lessThan(leaf->player))
  {
    if(leaf->left!=NULL){
     insert(p1, leaf->left);
     return false;
    }else
    {

      leaf->left=new node;
      leaf->left-> p1;
      leaf->left->left=NULL;    //Sets the left child of the child node to null
      leaf->left->right=NULL;   //Sets the right child of the child node to null
      return true;
    }  
  }
  else(p1.lessThan(leaf->player)))
  {
    if(leaf->right!=NULL)
      insert(p1, leaf->right);
      return false;

    else
    {
      leaf->right=new node;
      leaf->right->p1;
      leaf->right->left=NULL;  //Sets the left child of the child node to null
      leaf->right->right=NULL; //Sets the right child of the child node to null
      return true;
    }
  }
}



//in your main function

while(!infile.eof())
        {
            currP.read(infile);

            myTree.insert(currP, MyTree->pRoot);
        }
        infile.close();

答案 1 :(得分:0)

this is the full thing 

This is main.cpp
    #include <iostream>
    #include <fstream>
    #include <string>
    #include "BinaryTree.h"

    using namespace std;

    int main(void)
    {
        const int FILE = 100;
        char input[FILE];
        char output[FILE];
        ifstream infile;
        ofstream outfile;

        Player currP;
        Tree myTree;

        int i;

        cout << "Please enter the name of your input data file: ";
        cin >> input;

        infile.open(input);
        if(infile.fail())
        {
            cout << endl << "We're sorry, the file specificed could not be     opened!" << endl;
            return 0;
        }


        while(!infile.eof())
        {
            currP.read(infile);
            myTree -> pRoot;
            myTree.insert(currP);
        }
        infile.close();

    }


This is player.cpp

        #include <iostream>
    #include <string>
    #include <iomanip>
    #include "Player.h"

    using namespace std;

    Player::Player()
    {
        Initialize("unknown", "unknown", "tbd", 0.0);
    }

    void Player::Initialize(string first, string last, string pos, double avg)
    {
        firstn = first;
        lastn = last;
        position = pos;
        if (avg < 0) avg = -avg;
        batave = avg;
    }

    void Player::read(istream &input)
    {
        char temp[100];
        input >> temp;
        firstn = temp;
        input >> temp;
        lastn = temp;
        input >> temp;
        position = temp;
        input >> batave;
    }

    void Player::write(ostream &out)
    {
        out << lastn << ", " << firstn << ": " << position;
        out << fixed;
        out << setprecision(3);
        out << " (" << batave << ") ";
    }

    bool Player::lessThan(const Player &player) const
    {
        bool less;

        if(lastn.compare(player.lastn) < 0)
            less = true;
        else if (lastn.compare(player.lastn) == 0 && firstn.compare(player.firstn) < 0)
            less = true;
        else
            less = false;

        return less;
    }


player.h

        #include <iostream>
    using namespace std;

    class Player
    {
        private:
            string firstn;
            string lastn;
            string position;
            double batave;
        public:
            Player();
            void Initialize(string, string, string, double);

            void read(istream&);
            void write(ostream&);

            double getbatave();
            string getfirstname();
            string getlastname();
            string getfullname();
            string getposition();

            bool lessThan(const Player &player) const;
            bool equals (const Player &player) const;

    };

BinaryTree.cpp

        #include <iostream>
    #include <fstream>
    #include "BinaryTree.h"

    using namespace std;

    Node::Node()
    {

    }
    Tree::Tree()
    {

    }


    bool Tree::insert(Player player) //key is your player and leaf is parent node
    {
        Node *leaf;

        if(player < leaf -> item)
        {
            if(leaf -> left != NULL)
            {
                insert(player, leaf -> left);
                return false;
            }
            else
            {
                leaf -> left = new Node;
                leaf -> left -> item = player;
                leaf -> left -> left = NULL;    //Sets the left child of the child node to null
                leaf -> left -> right = NULL;   //Sets the right child of the child node to null
                return true;
            }  
        }
        else if(player > leaf -> item)
        {
            if(leaf -> right != NULL)
            {
                insert(player, leaf -> right);
                return false;
            }
            else
            {
                leaf -> right = new Node;
                leaf -> right -> item = player;
                leaf -> right -> left = NULL;  //Sets the left child of the child node to null
                leaf -> right -> right = NULL; //Sets the right child of the child node to null
                return true;
            }
        }
    }



    Tree::~Tree()
    {

    }

BinaryTree.h



    #include <iostream>
    #include <fstream>
    #include <string>
    #include <iomanip>
    #include "Player.h"
    using namespace std;

    class Node 
    {
    public: 
        Node();
        Player item;                // Storage space for a Player
        Node *left;                 // A pointer to the left
        Node *right;                    // A pointer to the right
        Node *pCurrent;
        Node *leaf;

        Node(const Player &player)      // Used to copy item into newly created nodes for our list
        {
            item = player;
            left = NULL;                // Set link to a valid non-node value
            right = NULL;
            leaf = NULL;
        }
    };

    class Tree
    {
        private: 
            int  length;                // Current length of the list (number of items stored)
            Node *pRoot;                // Node created to put root value into
            Node *pL;               // Node created to put value less than root value
            Node *pR;               // Node created to put value greater than root value


        public:
            Tree();                         // Constructor
            ~Tree();                        // Destructor

            bool insert(Player player);     // Adds a new player to the tree
            void free();                    // Cleans up a tree and free all of the   nodes in the tree
            void count();                   // Returns a count of all players in the tree
            void display();                 // Displays the player records, in appropriate order.
            void updateAvg();               // Updates a particular player's batting average
            void find();                    // Finds a player by name
    };


    I need to have these:
    default constructor and destructor
    insert - to add a new player to the tree
     free - to clean up a tree and free all of the nodes in the tree
     count - to return a count of all players in the tree
     display - to display the player records, in appropriate order.
     updateAvg - to update a particular player's batting average
     find - find a player by name

        the input file is this: 
        Chipper Jones 3B 0.303
    Rafael Furcal SS 0.281
    Hank Aaron RF 0.305
    Andrew Jones CF 0.322
    McKenna Wilson g3 0.245
    Finnigen Rengen 5f 0.245
    Landen Savage 2f 0.252
    Raschoie Sacoire 4f 0.632
    Joughne Seong h3 0.744
    Halmens Flamens g3 0.245
        enter code here