思路1:DFS
/**
* 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) {
if (!root) return nullptr;
TreeNode* right = invertTree(root->left);
TreeNode* left = invertTree(root->right);
root->left = left;
root->right = right;
return root;
}
};
思路2:BFS
- 层次遍历二叉树
- 对于每层的每个节点,都有左右孩子,那么交换每个节点的左右孩子,就相当于把整个二叉树翻转了一遍。
/**
* 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) {
if (!root) {
return root;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur_node = q.front();
q.pop();
if (cur_node->left || cur_node->right) {
// exchange
TreeNode* temp = cur_node->left;
cur_node->left = cur_node->right;
cur_node->right = temp;
}
if (cur_node->left) {q.push(cur_node->left);}
if (cur_node->right) {q.push(cur_node->right);}
}
return root;
}
};