同力扣226 :翻转二叉树
题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。

方法一:引入交换结点temp+递归
推荐函数代码一:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root)
{
return NULL;
}
TreeNode *temp=root->left;
root->left=root->right;
root->right=temp;
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
函数代码二:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return nullptr;
mirrorTree(root->left);
mirrorTree(root->right);
swap(root->left, root->right);
return root;
}
};
函数代码三:
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if (root == NULL) {
return NULL;
}
swap(root->left, root->right);
mirrorTree(root->left);
mirrorTree(root->right);
return root;
}
};
函数代码四:
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root)
{
return NULL;
}
TreeNode *temp=root->left;
root->left=mirrorTree(root->right);
root->right=mirrorTree(temp);
return root;
}
};
方法二:BFS+队列+层序遍历
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root)
{
return NULL;
}
queue<TreeNode *>q;
q.push(root);
while(!q.empty())
{
TreeNode *p=q.front();
q.pop();
if(p->left)
{
q.push(p->left);
}
if(p->right)
{
q.push(p->right);
}
swap(p->left,p->right);
}
return root;
}
};

本文详细介绍了四种不同的方法来实现二叉树的翻转,包括递归和BFS层序遍历等,提供了清晰的C++代码示例,帮助读者深入理解二叉树的镜像操作。
421

被折叠的 条评论
为什么被折叠?



