Hello,

Check this out

http://www.cplusplus.com/forum/general/3452/[^]

15,997,727 members

See more:

Hi there.

So i made a small program that is holding data in a Binary Tree, the data type is in a template. The code so far is working fine, it creating a binary tree given random numbers by priority order so the left child is always smaller at the parent or the right child. After this logic the highest number in the tree is far right bottom. Now my code is printing the tree in order. And then finds the largest number in the tree.

There is only 1 step im missing to finish, i have to delete(remove) that largest number from the tree, and then print it out again. I hope some one can help me with that. Here is the code i got so far:

So i made a small program that is holding data in a Binary Tree, the data type is in a template. The code so far is working fine, it creating a binary tree given random numbers by priority order so the left child is always smaller at the parent or the right child. After this logic the highest number in the tree is far right bottom. Now my code is printing the tree in order. And then finds the largest number in the tree.

There is only 1 step im missing to finish, i have to delete(remove) that largest number from the tree, and then print it out again. I hope some one can help me with that. Here is the code i got so far:

#include <iostream> #include <string> #include <cstdlib> using namespace std; template<class t=""> class BinaryTree { struct Node { T data; Node* lChildptr; Node* rChildptr; Node(T dataNew) { data = dataNew; lChildptr = NULL; rChildptr = NULL; } }; private: Node* root; void Insert(T newData, Node* &theRoot) { if(theRoot == NULL) { theRoot = new Node(newData); return; } if(newData < theRoot->data) Insert(newData, theRoot->lChildptr); else Insert(newData, theRoot->rChildptr); } void PrintTree(Node* theRoot) { if(theRoot != NULL) { PrintTree(theRoot->lChildptr); cout<< theRoot->data<<" , "; PrintTree(theRoot->rChildptr); } } T Largest( Node* theRoot) { if ( root == NULL ){ cout<<"There is no tree"; return -1; } if (theRoot->rChildptr != NULL) return Largest(theRoot->rChildptr); else { cout<<"\n Highest priority: "<<theRoot->data<<"\n"; theRoot->data=NULL; return theRoot->data; } }; public: BinaryTree() { root = NULL; } void AddItem(T newData) { Insert(newData, root); } void PrintTree() { PrintTree(root); } T Largest() { return Largest(root); } }; int main() { BinaryTree<int> *myBT = new BinaryTree<int>(); for(int i = 0; i < 10; i++) myBT->AddItem(rand() % 100); myBT->PrintTree(); myBT->Largest(); } </int></int></class></cstdlib></string></iostream>

when i try to use

deletemy prog crashes while i try to list the tree elements the second time. hmhm

Permalink

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900