首先构造结构体:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x), left(NULL), right(NULL) {};
};
自下而上实现方式:就是先依次遍历右节点再遍历左节点两者交换然后返回根节点,也就是逆后序遍历(后序遍历也可以实现在这里就不多写了)
class Solution {
private:
vector<vector<int>> res;
vector<int> rec;
public:
TreeNode* mirrorTree(TreeNode* root) {
if (!root) return root;
TreeNode* rightnode = mirrorTree(root->right);
TreeNode* leftnode = mirrorTree(root->left);
root->left = rightnode;
root->right = leftnode;
return root;
}
中间采用层序遍历打印二叉树结果更直观
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
if (root) {
q.push(root);
}
while (!q.empty()) {
int size = q.size();//更新队列大小
for (int i = 0; i < size; i++) {//将这一层节点全部弹出放入数组,并同时放入下一层节点,因为一个根节点要对应两个子节点判断哦
TreeNode* front = q.front();
rec.push_back(front->val);
q.pop();
if (front->left) {
q.push(front->left);
}
if (front->right) {
q.push(front->right);
}
}//放入子节点完成
res.push_back(rec);
rec.clear();
}
return res;
}
};
自上而下实现方式主要是先交换左右子节点,然后再去遍历子节点的左右节点
class Solution1 {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (!root) return root;
TreeNode* temp=root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
测试用例:
int main()
{
TreeNode* x1 = new TreeNode(4);
TreeNode* x2 = new TreeNode(2);
TreeNode* x3 = new TreeNode(7);
TreeNode* x4 = new TreeNode(1);
TreeNode* x5 = new TreeNode(3);
TreeNode* x6 = new TreeNode(6);
TreeNode* x7 = new TreeNode(9);
x1->left = x2;
x1->right = x3;
x2->left = x4;
x2->right = x5;
x3->left = x6;
x3->right = x7;
Solution* x = new Solution;
vector<vector<int>> res;
x->mirrorTree(x1);
res = x->levelOrder(x1);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << res[i][j] << " ";
}
cout << endl;
}
}
结果跟上图一致