MushinZero MushinZero - 1 month ago 8
C++ Question

Binary search tree two similar functions producing garbage

I've got this call

productTree.displayNode(productTree.newsearchTree(search, productTree.Root()));


Calling these functions

void Tree::displayNode(Node* node) {
if (node != NULL) {
cout << node->productdata << endl;
}
}

Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
newsearchTree(search, node->left);
if (search == node->productdata.getName()) {
return node;
}
newsearchTree(search, node->right);
}
}

Node* Root() { return root; };


Which produces a garbage output when trying to display the returned node.

And yet, I can traverse my tree and display it easily this way:

This call:

productTree.Inorder(productTree.Root());


Functions:

void Tree::Inorder(Node* node) {
if (node != NULL) {
Inorder(node->left);
displayNode(node);
Inorder(node->right);
}
}


And where I am confused is how are they different?

Edit: Thank you for your help, I modified the code as below and it works fine now:

Node* Tree::newsearchTree(string search, Node* node) {
if (node != NULL) {
newsearchTree(search, node->left);
if (search == node->productdata.getName()) {
return node;
}
newsearchTree(search, node->right);
}
return NULL;
}

void Tree::displayNode(Node* node) {
if (node != NULL) {
cout << node->productdata << endl;
}
else if (node == NULL) {
cout << "Product not found" << endl;
}
}

Answer

Let me add comments inline to make it clear what your Tree::newsearchTree does.

Node* Tree::newsearchTree(string search, Node* node) {
  if (node != NULL) {
    newsearchTree(search, node->left);  // burn CPU but leaves no side effect
    if (search == node->productdata.getName()) {
      return node;  // return node only if the root node equals 'search'
    }
    newsearchTree(search, node->right);  // burn CPU without side effect
  }
  // In majority of the cases (root node != 'search'): return nothing.
}

Because typically newsearchTree() returns nothing, when you call productTree.displayNode(productTree.newsearchTree(...)) you basically print garbage.

Comments