题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \
11 9 7 5
思路:
前序遍历这个树,如果结点由子节点,则交换它的两个子节点(NULL也算),直到叶子结点全部交换后,则得到镜像。
代码:
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot==NULL)
return;
TreeNode*lr=NULL;
TreeNode*rr=NULL;
if(pRoot->left)
lr=pRoot->left;
if(pRoot->right)
rr=pRoot->right;
pRoot->left=rr;
pRoot->right=lr;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
不使用递归,使用循环的做法:就是使用队列
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot==NULL)
return;
deque<TreeNode*>node;
node.push_back(pRoot);
while(!node.empty())
{
TreeNode*cur=node.front();
node.pop_front();
TreeNode*lr=NULL;
if(cur->left)
lr=cur->left;
cur->left=cur->right;
cur->right=lr;
if(cur->left)//一定要有if语句,不然会造成死循环,一直往node里push_back#,pop_front#
node.push_back(cur->left);
if(cur->right)//一定要有if语句,不然会造成死循环,一直往node里push_back#,pop_front#
node.push_back(cur->right);
}
}
};