操作給定的二叉樹(shù),將其變換為源二叉樹(shù)的鏡像。 輸入描述:
二叉樹(shù)的鏡像定義:源二叉樹(shù)
8
/ 6 10
/ \ / 5 7 9 11
鏡像二叉樹(shù)
8
/ 10 6
/ \ / 11 9 7 5
方法一
/*
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;
}
TreeNode *tmp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = tmp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
方法二:
class Solution {
public:
//棧的非遞歸
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);
}
} //隊(duì)列的非遞歸
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);
}
}
//遞歸
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)return;
swap(pRoot->left, pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};