Q:操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
A:
1.递归完成
void Mirror(TreeNode *pRoot) {
if(pRoot){
TreeNode* temp = pRoot->right;
pRoot->right = pRoot->left;
pRoot->left = temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
}
2.栈的非递归
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)return;
stack<TreeNode*> st;
TreeNode* p = NULL;
st.push(pRoot);
while (st.size())
{
p = st.top();
st.pop();
swap(p->left, p->right);
if (p->left)st.push(p->left);
if (p->right)st.push(p->right);
}
}
3.队列的非递归
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)return;
queue<TreeNode*> qu;
TreeNode* p = NULL;
qu.push(pRoot);
while (qu.size())
{
p = qu.front();
qu.pop();
swap(p->left, p->right);
if (p->left)qu.push(p->left);
if (p->right)qu.push(p->right);
}
}
原文:https://www.cnblogs.com/xym4869/p/12256620.html