1 分治法-递归
代码语言:javascript
复制/**
* 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;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
2 BFS
代码语言:javascript
复制class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
queue<TreeNode*> q;
q.push(root);
TreeNode* node = new TreeNode(root->val);
while (!q.empty()) {
int sz = q.size();
for (int i=0;i < sz;i ) {
TreeNode* e_ptr = q.front(); q.pop();
swap(e_ptr->left, e_ptr->right);
if (e_ptr->right) q.push(e_ptr->right);
if (e_ptr->left) q.push(e_ptr->left);
}
}
return root;
}
};