https://leetcode.com/problems/invert-binary-tree/

1. Use recursion:

  1. //4 ms 8.5 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  10. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  11. * };
  12. */
  13. class Solution {
  14. public:
  15. TreeNode* invertTree(TreeNode* root) {
  16. if(!root) return NULL;
  17. TreeNode* left = invertTree(root->left);
  18. TreeNode* right = invertTree(root->right);
  19. root->left = right;
  20. root->right = left;
  21. return root;
  22. }
  23. };

Time complexity: O(n)
Space complexity: O(n)