Skip to content

Instantly share code, notes, and snippets.

@piusayowale
Created February 1, 2022 14:16
Show Gist options
  • Save piusayowale/dc1bbccedc10693ec5ee7b9a894557e0 to your computer and use it in GitHub Desktop.
Save piusayowale/dc1bbccedc10693ec5ee7b9a894557e0 to your computer and use it in GitHub Desktop.
invert binary search tree
struct Node {
int value;
Node* left;
Node* right;
};
Node* insert(Node* list, int value) {
if (list == nullptr) {
Node* temp = new Node;
temp->value = value;
temp->left = nullptr;
temp->right = nullptr;
return temp;
}
if (value < list->value) {
list->left = insert(list->left, value);
}
else {
list->right = insert(list->right, value);
}
return list;
}
void swap(Node* &a, Node*& b) {
Node* temp = a;
a = b;
b = temp;
}
Node* invert(Node* list) {
if (list == NULL) {
return list;
}
list->left = invert(list->left);
list->right = invert(list->right);
swap(list->left, list->right);
return list;
}
void print(Node* list) {
if (list == nullptr) {
return;
}
print(list->left);
std::cout << list->value << " ";
print(list->right);
}
int main() {
Node* list = nullptr;
list = insert(list, 4);
list = insert(list, 1);
list = insert(list, 9);
list = insert(list, 7);
list = insert(list, 0);
list = insert(list, 3);
list = insert(list, 5);
print(list);
std::cout << "\n";
list = invert(list);
print(list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment