题目描述

具体链接:https://leetcode-cn.com/problems/invert-binary-tree/

解题思路

递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. TreeNode* invertTree(TreeNode* root) {
  15. if (root == NULL)
  16. return root;
  17. if (root->left == NULL && root->right == NULL)
  18. return root;
  19. if (root->left == NULL && root->right != NULL) {
  20. root->left = invertTree(root->right);
  21. root->right = NULL;
  22. return root;
  23. }
  24. if (root->left != NULL && root->right == NULL) {
  25. root->right = invertTree(root->left);
  26. root->left = NULL;
  27. return root;
  28. }
  29. TreeNode* temp_left = invertTree(root->left);
  30. TreeNode* temp_right = invertTree(root->right);
  31. root->left = temp_right;
  32. root->right = temp_left;
  33. return root;
  34. }
  35. };