時間限制:1秒 空間限制:32768K
題目描述
操作給定的二叉樹,將其變換為源二叉樹的鏡像构罗。
輸入描述
/*
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==nullptr)
return;
TreeNode* tmp=pRoot->left;
pRoot->left=pRoot->right;
pRoot->right=tmp;
if(pRoot->left)
Mirror(pRoot->left);
if(pRoot->right)
Mirror(pRoot->right);
return;
}
};
運行時間:8ms
占用內(nèi)存:592k
/*
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==nullptr)
return;
stack<TreeNode*> st;
st.push(pRoot);
while(!st.empty()){
TreeNode* root=st.top();st.pop();
if(root->left || root->right){
TreeNode* tmp=root->left;
root->left=root->right;
root->right=tmp;
}
if(root->left)
st.push(root->left);
if(root->right)
st.push(root->right);
}
return;
}
};
運行時間:4ms
占用內(nèi)存:496k