方法1:递归实现
先把根节点的左右子树交换,再对左子树、右子树进行同样的操作。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
TreeNode *temp;
temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
方法2:非递归实现
既可以用队列辅助,也可以用栈辅助。如果用队列,先把根节点的左右子树交换,然后把左右子树入队列,每次取出队首元素,交换左右子树,直到队列为空。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
queue<TreeNode*> qq;
qq.push(pRoot);
TreeNode *node, *temp;
while(!qq.empty()){
node = qq.front();
temp = node->left;
node->left = node->right;
node->right = temp;
qq.pop();
if(node->left)
qq.push(node->left);
if(node->right)
qq.push(node->right);
}
}
};
如果用栈,则先把根节点的左右子树交换,然后把左右子树分别入栈,每次取栈顶元素,交换左右子树,直到栈为空。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
stack<TreeNode*> ss;
TreeNode *node, *temp;
ss.push(pRoot);
while(!ss.empty()){
node = ss.top();
ss.pop();
temp = node->left;
node->left = node->right;
node->right = temp;
if(node->left)
ss.push(node->left);
if(node->right)
ss.push(node->right);
}
}
};