你好. 所以我做了一个小程序,将数据保存在二叉树中,数据类型在模板中.到目前为止,该代码运行良好,它会按优先级顺序创建一个由随机数指定的二叉树,因此左子级始终在父级或右子级较小.按照这种逻辑,树中的最高数字位于最右下角.现在我的代码是按顺序打印树.然后在树中找到最大的数字. 我只剩下1个步骤想完成,我必须从树中删除(删除)最大的数字,然后再次打印出来.我希望有人可以帮助我.这是到目前为止我得到的代码:
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:
#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>推荐答案
您好, 看看这个 www.cplusplus/forum/general/3452/ [ ^ ] Hello, Check this out www.cplusplus/forum/general/3452/[^]
当我尝试使用时 delete
当我第二次尝试列出树元素时,我的编崩溃了. hmhm
my prog crashes while i try to list the tree elements the second time. hmhm
更多推荐
从二叉树中删除
发布评论