题目:操作给定的二叉树,将其变换为源二叉树的镜像。
思路:利用栈进行存储二叉树的节点,需要镜像时弹出,然后把左子树和右子树进行交换。此处不考虑递归解法
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot)
{
if (pRoot == NULL)
return ;
stack<TreeNode *>stackNode;
stackNode.push(pRoot);
while (stackNode.size())
{
TreeNode *tree = stackNode.top();
stackNode.pop();
if (tree->left != NULL || tree->right != NULL)
{
TreeNode *temp;
temp = tree->right;
tree->right = tree->left;
tree->left = temp;
}
if (tree->left)
{
stackNode.push(tree->left);
}
if (tree->right)
{
stackNode.push(tree->right);
}
}
}
};