Created
February 1, 2022 14:16
-
-
Save piusayowale/dc1bbccedc10693ec5ee7b9a894557e0 to your computer and use it in GitHub Desktop.
invert binary search tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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