1. 递归
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return pRoot;
swap(pRoot->left, pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
return pRoot;
}
};
2. 层序遍历
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return pRoot;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
TreeNode* tmp_node = q.front();
q.pop();
swap(tmp_node->left, tmp_node->right);
if (tmp_node->left) q.push(tmp_node->left);
if (tmp_node->right) q.push(tmp_node->right);
}
}
return pRoot;
}
};