I was thinking of implementing a little program using a BST. Which basically moves through the tree and inserts a value based on user input. However the node values are only strings and we branch through based on user input such as for example in this tree:
alpha1 / \ alpha 2 alpha 2 / \ / \ N1 N2 N3 N4 where alpha1 and alpha2 are strings Nx is NULL pointer and x is a number {1...infinity} For example if a user provided a string of "10" and number to replace "66" the program would go to pointer N3 as 1 = tree_right and 0 = tree_left and replace it with the number 66.
Right now I can do this manually as such:
t->right->left = add_tree("66", 0,0);
And my program currently implements the alpha tree above but I have yet to implement the functionality for adding it via subroutines/recursion as this tree could go to alpha10 in depth and I can't manually do it.
This code implements the alpha tree
struct TreeNode{ std::string val; TreeNode* left; TREENode* right; }; TreeNode* add_tree(std::string value, TreeNode* l, TreeNode* r){ TreeNode* tmp; tmp = new TreeNode; tmp->val = value; tmp->left = l; tmp->right = r; return tmp; } // This makes the alpha tree with the null pointers TreeNode* insertion_tree(std::string e, TreeNode* t){ if(t == NULL){ return add_tree(e, 0,0); } else if(e == "alpha"){ t->left = insertion_tree(e, t->left); t->right = insertion_tree(e, t->right); return t; } else{ return 0; } } I tried this sort of for-loop but as I keep on re-declaring the pointer it causes the previous tree to be forgotten and it just created a tree with the element I inserted
// This should give me the location of the node I want to replace after traversing e.g:"01" TreeNode* replace_null(std::string e, TreeNode* t){ for(int i=0;i<e.length();i++){ if(e[i] == "0"){ tmp = tmp->left; } if(e[i] == "1"){ tmp = tmp->right; } } return tmp; } It would be a lifesaver if anybody could help me as I've been stuck on replacing the NULL for a couple of hours.
https://stackoverflow.com/questions/66630948/searching-through-a-bst-based-on-user-input-c March 15, 2021 at 08:28AM
没有评论:
发表评论