Last active
September 3, 2022 20:22
-
-
Save ICyperior/47cc65f9e6292e2bec8b8947a646fce0 to your computer and use it in GitHub Desktop.
Reverse a binary tree.
This file contains 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
#include <iostream> | |
#include <vector> | |
#include <queue> | |
class Node { | |
public: | |
int data; | |
Node* left, * right; | |
Node(int data) { | |
this->data = data; | |
left = right = NULL; | |
} | |
}; | |
void reverseBinaryTree(Node*& tree) { | |
if (tree == 0) | |
return; | |
std::swap(tree->left, tree->right); | |
reverseBinaryTree(tree->left); | |
reverseBinaryTree(tree->right); | |
} | |
Node* insert(Node* root, int data) { | |
if (root == NULL) { | |
return new Node(data); | |
} | |
else { | |
Node* cur; | |
if (root->left == NULL) { | |
cur = insert(root->left, data); | |
root->left = cur; | |
} | |
else { | |
cur = insert(root->right, data); | |
root->right = cur; | |
} | |
return root; | |
} | |
} | |
void printTree(Node* root) { | |
if (root == 0) | |
return; | |
std::queue<Node*> q; | |
q.push(root); | |
while (q.empty() == false) { | |
Node* node = q.front(); | |
std::cout << node->data << " "; | |
q.pop(); | |
if (node->left != NULL) | |
q.push(node->left); | |
if (node->right != NULL) | |
q.push(node->right); | |
} | |
std::cout << std::endl; | |
} | |
int main(int argc, char const* argv[]) | |
{ | |
std::vector<int> data = { 1,2,3,4,5,6,7,8,9 }; | |
int size = data.size(); | |
Node* bTree = NULL; | |
int i = 0; | |
while (i < size) | |
bTree = insert(bTree, data[i++]); | |
printTree(bTree); | |
reverseBinaryTree(bTree); | |
printTree(bTree); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment