27.二叉树的镜像*
题目描述*
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
示例*
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
代码*
递归、迭代
class Solution {
public:
void mirror(TreeNode *root) {
if(root == nullptr) {
return;
}else {
TreeNode *cur = root->left;
root->left = root->right;
root->right = cur;
mirror(root->left);
mirror(root->right);
}
}
TreeNode* mirrorTree(TreeNode* root) {
mirror(root);
return root;
}
};
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
stack<TreeNode*> helpStack;
TreeNode *cur = root, *tmp = root;
while(cur != nullptr || !helpStack.empty()) {
while(cur != nullptr) {
tmp = cur->left;
cur->left = cur->right;
cur->right = tmp;
helpStack.push(cur);
cur = cur->left;
}
cur = helpStack.top();
helpStack.pop();
cur = cur->right;
}
return root;
}
};
最后更新: July 23, 2022