【发布时间】:2020-07-25 10:26:53
【问题描述】:
如何更改树中所有节点的值?
我用多个键值填充了我的 BST 树。
一切正常,我只是不知道如何通过在它们上添加 log2 来更改所有节点的值。
如何遍历每个节点?
我的 Node.hpp
class Node{
private:
Node *left; //left child
Node *right; //right child
std::string num;
public:
int data; //number
Node(); //constructor
void setData(string num, int data); //sets number in node
string getData(); //return numbers from node
int &getOcc();
void setLeft(Node *l); //sets left child pointer
Node* &getLeft(); //returns left child pointer
void setRight(Node *r); //sets right child pointer
Node* &getRight(); //return right child pointer
};
我的 BST.hpp
class BST{
private:
Node * root; //root node pointer
public:
BST(); //constructor
~BST(); //destructor
void Insert(string num, int data); //Inserts new number in tree
void InsertIDF(string num, int data); //Inserts new number in tree
bool find(string num); //finds whether a number is present in tree
void min(); //find and print minimum number in the tree
void max(); //find and print maximum number in the tree
void save_file(string filename); //save the tree to file
void Delete(string num); //deletes a number from tree
void LoadFromFile(string filename); //loads numbers from file to tree
void Print(); //print tree to stdout
//private functions used as helper functions in the public operations
private:
void printHelper(Node *root);
bool findHelper(Node *root,string num);
void InsertHelper(Node * ¤t, string num, int data);
void InsertHelperIDF(Node * ¤t, string num, int data);
void findMinHelper(Node* current);
void findMaxHelper(Node * current);
void saveHelper(ofstream &fout, Node* current);
Node* DeleteHelper(Node *current, string num);
Node * findMaximum(Node * n);
void clear(Node *currnt);
};
【问题讨论】:
-
通过递归,改变当前节点的一个值,然后调用兄弟节点的改变
-
你的意思是,我创建了一个函数来更改值并在其中调用它?
-
您想将 log(2)_base10 添加到树中的每个节点?如果我有来自单个节点的值,我该如何修改它以获得你想要的结果?
-
我会在一秒钟内编辑我的帖子
-
为什么要将数字存储在字符串中?好吧,您可以添加一个方法,该方法将指向节点的指针作为输入,增加此 $\log_2$ 存储的值,然后从 silbling 节点调用此方法。为根节点调用此方法
标签: c++ tree binary-search-tree