關(guān)鍵詞:
思路:
//交換根節(jié)點的左右子節(jié)點
//交換根節(jié)點左子節(jié)點的左右子節(jié)點
//交換根節(jié)點右子節(jié)點的左右子節(jié)點
自己的解法:
struct BinaryTreeNode{
int m_nKey;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int nVal) :m_nKey(nVal), m_pLeft(nullptr), m_pRight(nullptr)
{}
};
//二叉樹鏡像
void Mirror(BinaryTreeNode* pHead)
{
//交換根節(jié)點的左右子節(jié)點
//交換根節(jié)點左子節(jié)點的左右子節(jié)點
//交換根節(jié)點右子節(jié)點的左右子節(jié)點
if (pHead == nullptr)
return;
BinaryTreeNode* pTmp = pHead->m_pLeft;
pHead->m_pLeft = pHead->m_pRight;
pHead->m_pRight = pTmp;
Mirror(pHead->m_pLeft);
Mirror(pHead->m_pRight);
}
標準答案:
/*
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) {
//1.如果是空節(jié)點的話,返回
if(pRoot==nullptr)
return;
//2.如果是葉子節(jié)點的話劣欢,返回裁良,
if(pRoot->left == nullptr && pRoot->right == nullptr)
return;
//3.先交換根節(jié)點的左右節(jié)點
TreeNode* tmpNode = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = tmpNode;
//4.操作左子樹
Mirror(pRoot->left);
//5.操作右子樹
Mirror(pRoot->right);
}
};