
g0201_0300.s0226_invert_binary_tree.Solution.c Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-all Show documentation
Show all versions of leetcode-in-all Show documentation
104 LeetCode algorithm problem solutions
// #Easy #Top_100_Liked_Questions #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree
// #Data_Structure_I_Day_12_Tree #Level_2_Day_6_Tree #Udemy_Tree_Stack_Queue
// #Big_O_Time_O(n)_Space_O(n) #2024_11_06_Time_0_ms_(100.00%)_Space_8.4_MB_(85.55%)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#include
#include
// Function to invert a binary tree
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL) {
return NULL;
}
// Swap the left and right children
struct TreeNode* temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return root;
}
// Helper function to create a new tree node
struct TreeNode* createNode(int val) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->val = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Helper function to print the tree in order (for testing purposes)
void printInOrder(struct TreeNode* root) {
if (root == NULL) return;
printInOrder(root->left);
printf("%d ", root->val);
printInOrder(root->right);
}
// Helper function to free the tree memory
void freeTree(struct TreeNode* root) {
if (root == NULL) return;
freeTree(root->left);
freeTree(root->right);
free(root);
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy