1. Clone Mirror Tree Recursively
Intuition
Create a new TreeNode for root, and set its left to cloneInvert(root.right) and its right to cloneInvert(root.left).
When to apply: When the input tree must remain immutable.
Algorithm
- Step 1: If root == null return null.
- Step 2: Create new TreeNode copy(root.val).
- Step 3: copy.left = cloneInvert(root.right).
- Step 4: copy.right = cloneInvert(root.left). Return copy.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: TreeNode* invertTree(TreeNode* root) { if (!root) return nullptr; TreeNode* copy = new TreeNode(root->val); copy->left = invertTree(root->right); copy->right = invertTree(root->left); return copy; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Allocates n new nodes. - Space complexity:
O(n)— O(n) new memory for copied tree nodes.