Mental Model
Flipping a binary tree means swapping every left child with its right child, all the way down.
Analogy: Imagine holding a tree-shaped mirror and seeing the tree's reflection flipped left to right.
1 / \ 2 3 / \ 4 5
1 / \ 2 3 / \ 4 5
1
/ \
3 2
/ \
4 5 1
/ \
3 2
/ \
4 5 1
/ \
3 2
/ \
5 4 1
/ \
3 2
/ \
5 4 1
/ \
3 2
/ \
5 4#include <stdio.h> #include <stdlib.h> // Define a binary tree node typedef struct Node { int data; struct Node* left; struct Node* right; } Node; // Create a new node Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = NULL; node->right = NULL; return node; } // Mirror the binary tree by swapping left and right children recursively void mirror(Node* root) { if (root == NULL) return; // base case: empty node // swap left and right children Node* temp = root->left; root->left = root->right; root->right = temp; mirror(root->left); // mirror left subtree mirror(root->right); // mirror right subtree } // Print tree in preorder to show structure void preorderPrint(Node* root) { if (root == NULL) return; printf("%d ", root->data); preorderPrint(root->left); preorderPrint(root->right); } int main() { // Build tree: 1 // / \ // 2 3 // / \ // 4 5 Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Original tree preorder: "); preorderPrint(root); printf("\n"); mirror(root); printf("Mirrored tree preorder: "); preorderPrint(root); printf("\n"); return 0; }
if (root == NULL) return;Node* temp = root->left;
root->left = root->right;
root->right = temp;mirror(root->left);mirror(root->right);if (root == NULL) return;
if (root == NULL) return;
Node* temp = root->left; root->left = root->right; root->right = temp;
struct Node {
int data;
struct Node* left;
struct Node* right;
};
void mirrorTree(struct Node* root) {
if (root == NULL) return;
struct Node* temp = root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->left);
mirrorTree(root->right);
}
// Tree before mirror:
// 1
// / \
// 2 3
// / \
// 4 5
// After mirror, print preorder traversal:
// Expected output?
void mirrorTree(struct Node* root) {
if (root == NULL) return;
mirrorTree(root->left);
struct Node* temp = root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->right);
}Pass the test and this pattern moves unknown