题目描述
输入一棵二叉树,输出它的镜像
思路:遍历二叉树,左右儿子交换
void MirrorRecursively(BinaryTreeNode *pNode)
{
if(pNode==nullptr)
return;
if(pNode->m_pLeft == nullptr && pNode->m_pRight == nullptr)
return;
BinaryTreeNode *tmp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = tmp;
MirrorRecursively(pNode->m_pLeft);
MirrorRecursively(pNode->m_pRight);
}
leetcode
- 翻转二叉树
翻转一棵二叉树
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
if(root->left==nullptr && root->right == nullptr) return root;
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
if(root->left)
root->left = invertTree(root->left);
if(root->right)
root->right = invertTree(root->right);
return root;
}
};
执行用时 : 0 ms, 在Invert Binary Tree的C++提交中击败了100.00% 的用户
内存消耗 : 9.6 MB, 在Invert Binary Tree的C++提交中击败了5.20% 的用户