解法1:递归
思想:
分解为子问题:镜像后root->right是原来root->left的镜像,root->left同理
代码:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root == NULL)
return NULL;
//不能直接赋给root->left,会覆盖本来的左子树
TreeNode* new_left = mirrorTree(root->right);
TreeNode* new_right = mirrorTree(root->left);
root->left = new_left;
root->right = new_right;
return root;
}
};
复杂度:
●时间复杂度:O(N),其中N为二叉树的节点数,建立镜像需要遍历树的所有节点,占用O(N)时间
●空间复杂度:O(N),最差情况下二叉树退化为链表,需要递归N层,需要O(N)大小的栈空间。
解法2:迭代
思想:
利用栈(或队列)遍历树的所有节点,并交换每个节点的左/右子节点
复杂度:
●时间复杂度:O(N),需要遍历所有节点
●空间复杂度:O(N),满二叉树时,栈最多同时存储N/2个节点,占用O(N)空间
代码:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root == NULL)
return NULL;
stack<TreeNode*>stack;
stack.push(root);
while(!stack.empty()){
TreeNode* cur = stack.top();
stack.pop();
//不为空才加入
if(cur->left != NULL)
stack.push(cur->left);
if(cur->right != NULL)
stack.push(cur->right);
//交换
swap(cur->left, cur->right);
}
return root;
}
};