image.png

思路1:DFS

  • 利用递归的结构进行翻转
  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) return nullptr;
  16. TreeNode* right = invertTree(root->left);
  17. TreeNode* left = invertTree(root->right);
  18. root->left = left;
  19. root->right = right;
  20. return root;
  21. }
  22. };

思路2:BFS

  • 层次遍历二叉树
  • 对于每层的每个节点,都有左右孩子,那么交换每个节点的左右孩子,就相当于把整个二叉树翻转了一遍。
  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) {
  16. return root;
  17. }
  18. queue<TreeNode*> q;
  19. q.push(root);
  20. while (!q.empty()) {
  21. TreeNode* cur_node = q.front();
  22. q.pop();
  23. if (cur_node->left || cur_node->right) {
  24. // exchange
  25. TreeNode* temp = cur_node->left;
  26. cur_node->left = cur_node->right;
  27. cur_node->right = temp;
  28. }
  29. if (cur_node->left) {q.push(cur_node->left);}
  30. if (cur_node->right) {q.push(cur_node->right);}
  31. }
  32. return root;
  33. }
  34. };