My program goal is to search for a tree node with a given key using depth-first search and if a node with that key is found it will be returned to the caller function. The problem is that accessing the node after DFS execution terminates the program with a segmentation fault, exactly when it searches for a node in the right subtree, but not when searching on the left subtree.
This is the source code:
#include <iostream>
using namespace std;
struct node
char data;
struct node *left;
struct node *right;
};
struct node *root = nullptr;
struct node* addNewNode(char newData) {
struct node* newNode = new node;
newNode->data = newData;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
struct node* preOrder(struct node *srcNode, char key) {
if (srcNode != nullptr) {
if (srcNode->data == key)
return srcNode;
return preOrder(srcNode->left, key);
return preOrder(srcNode->right, key);
}
}
int main() {
root = addNewNode('a');
root->left = addNewNode('e');
root->right = addNewNode('c');
root->left->left = addNewNode('h');
root->left->right = addNewNode('z');
struct node* res = preOrder(root, 'c');
cout << res->data;
return 0;
}