二叉树的镜像
描述
给定二叉树,将其变换为原二叉树的镜像
原二叉树
镜像二叉树
输入:{8,6,10,5,7,9,11}
输出:{8,10,6,11,9,7,5}
思路1:递归方法:从最左侧开始,将左右孩子相互交换,然后递归向根节点方向开始交换。递归+交换
class Solution {
public:
void HOU(TreeNode* pRoot)
{
if(!pRoot) return;
//后续遍历
Mirror(pRoot->left);
Mirror(pRoot->right);
//交换左右子树,如果左右子树都不存在,没有交换操作
if(pRoot->left || pRoot->right)
{
TreeNode* temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
}
}
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
if(!pRoot) return nullptr;
HOU(pRoot);
return pRoot;
}
};
思路2:非递归。采用栈和层次遍历的思想从顶层到底层进行遍历操作
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
// write code here
//非递归,利用栈和层次遍历的思想进行操作
if (!pRoot) return nullptr;
stack<TreeNode*> stack;
stack.push(pRoot);
while (!stack.empty()) {
TreeNode* temp = stack.top();
if (temp->left || temp->right) {
TreeNode* tem = temp->left;
temp->left = temp->right;
temp->right = tem;
}
stack.pop();
if (temp->left)
stack.push(temp->left);
if (temp->right)
stack.push(temp->right);
}
return pRoot;
}
};