Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Created March 8, 2020 11:46
Show Gist options
  • Save pedrominicz/94bdd1faa07d9856d96e45be56a23604 to your computer and use it in GitHub Desktop.
Save pedrominicz/94bdd1faa07d9856d96e45be56a23604 to your computer and use it in GitHub Desktop.
Mirror a binary tree in C.
#include <assert.h>
#include <stdio.h>
#define swap(x, y) { void* tmp = x; x = y; y = tmp; }
typedef struct node_t* tree_t;
typedef struct node_t {
int elem;
tree_t left, right;
} node_t;
void invert_tree(tree_t* tree) {
if(!*tree) return;
invert_tree(&(*tree)->left);
invert_tree(&(*tree)->right);
swap((*tree)->left, (*tree)->right);
}
void print_tree(tree_t tree) {
if(!tree) return;
print_tree(tree->left);
printf("%d ", tree->elem);
print_tree(tree->right);
}
int main(void) {
// Test tree:
//
// 4 4
// / \ / \
// 2 5 ==> 5 2
// / \ / \
// 1 3 3 1
//
node_t _1 = { 1, NULL, NULL };
node_t _3 = { 3, NULL, NULL };
node_t _2 = { 2, &_1, &_3 };
node_t _5 = { 5, NULL, NULL };
node_t _4 = { 4, &_2, &_5 };
tree_t root = &_4;
print_tree(root);
invert_tree(&root);
print_tree(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment