Leetcode 226. Invert Binary Tree
Leetcode Problem 226: Invert Binary Tree
Given the root
of a binary tree, invert the tree, and return its root.
For example, if the input binary tree is:
4
/ \
2 7
/ \ / \
1 3 6 9
The inverted binary tree is:
4
/ \
7 2
/ \ / \
9 6 3 1
[0, 100]
.root
is null
?
null
, the function should return null
.To invert a binary tree, we need to swap the left and right children at each node. We can achieve this using either recursion or iteration.
null
, return null
.We will use the recursive approach in this solution because it is more intuitive and simpler to implement for binary tree problems.
The time complexity for both the recursive and iterative approaches is O(n), where n is the number of nodes in the binary tree. Each node is visited once, and a constant amount of work is done per node.
Here’s the implementation of the recursive approach in C++:
#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
// Base case: if the tree is empty, return null
if (root == nullptr) {
return nullptr;
}
// Swap the left and right children of the current node
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
// Recursively invert the left subtree and right subtree
invertTree(root->left);
invertTree(root->right);
return root;
}
};
// Usage example
int main() {
TreeNode* root = new TreeNode(4);
root->left = new TreeNode(2);
root->right = new TreeNode(7);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(3);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(9);
Solution sol;
TreeNode* invertedRoot = sol.invertTree(root);
// Output the result (for testing purposes)
// Expected output should show the structure of the inverted tree
std::cout << "Root: " << invertedRoot->val << std::endl;
std::cout << "Left child: " << invertedRoot->left->val << std::endl;
std::cout << "Right child: " << invertedRoot->right->val << std::endl;
return 0;
}
This solution will correctly invert a binary tree using a recursive approach. The main function shows how to use the invertTree
function and print the results for testing purposes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?