I am attempting to write a program that will find a circular reference (reference to a parent or ancestor) within a binary tree that has no clear sorting order.
The Node class constructor is as follows:
int key;
Node* left;
Node* right;
Node(int nodeKey, Node* leftChild = nullptr, Node* rightChild = nullptr) {
key = nodeKey;
left = leftChild;
right = rightChild;
}
The section of the client program that my solution fails on is as follows:
Node* rootRight = new Node(89);
root = new Node(87, new Node(51), rootRight);
badNode = new Node(91, rootRight, nullptr);
rootRight->right = badNode;
// Call the user's CheckBSTValidity() function
userResult = BSTChecker::CheckBSTValidity(root);
// Check the user's result
if (badNode == userResult) {
cout << "CheckBSTValidity() correctly returned the rule-violating node." << endl;
}
else if (nullptr == userResult) {
cout << "CheckBSTValidity() returned nullptr for an invalid tree." << endl;
}
else {
cout << "CheckBSTValidity() returned a node that is not the BST ";
cout << "rule-violating node." << endl;
}
// Remove the circular reference, then delete the tree
rootRight->right = nullptr;
Node::DeleteTree(root);
// Create the invalid tree wherein a node has a child that references an
// ancestor. The ancestor is NOT the immediate parent, nor the root.
root = new Node(51, new Node(27, new Node(14), nullptr), nullptr);
badNode = new Node(92);
Node* node83 = new Node(83, new Node(77), badNode);
Node* node72 = new Node(72, nullptr, node83);
badNode->left = node72;
root->right = node72;
// Call the user's CheckBSTValidity() function
userResult = BSTChecker::CheckBSTValidity(root);
// Check the user's result
if (badNode == userResult) {
cout << "CheckBSTValidity() correctly returned the rule-violating node." << endl;
}
else if (nullptr == userResult) {
cout << "CheckBSTValidity() returned nullptr for an invalid tree." << endl;
}
else {
cout << "CheckBSTValidity() returned a node that is not the BST ";
cout << "rule-violating node." << endl;
}
And my program to check if a specific node violates the condition is as follows:
static bool CheckIsDescendant(Node* root, Node* descendant){
if (root == nullptr){
return false;
}
if (root == descendant){
return true;
}
return CheckIsDescendant(root->left, descendant) || CheckIsDescendant(root->right, descendant);
}
static Node* CheckChildrenAreParents(Node* node){
if (node == nullptr){
return nullptr;
}
Node* left = CheckChildrenAreParents(node->left);
if (left != nullptr){
return left;
}
if ((node->left && CheckIsDescendant(node->left, node)) || (node->right && CheckIsDescendant(node->right, node))){
return node;
}
Node* right = CheckChildrenAreParents(node->right);
if (right != nullptr){
return right;
}
return nullptr;
}
The program is segfaulting
