二叉树的镜像
1.题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
2.方法1(递归)
利用二叉树的先序遍历,交换每个节点的左右子节点。
3.代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root == NULL){
return NULL;
}
swap(root->left, root->right);
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
4.复杂度分析
时间复杂度:O(n)
空间复杂度:O(n)
5.方法2(栈)
通过栈模拟二叉树的先序遍历,交换每个节点的左右子节点。
6.代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root == NULL){
return NULL;
}
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* node = s.top();
s.pop();
swap(node->left, node->right);
if(node->left){
s.push(node->left);
}
if(node->right){
s.push(node->right);
}
}
return root;
}
};
7.复杂度分析
时间复杂度:O(n)
空间复杂度:O(n)