二叉树翻转镜像
程序员文章站
2022-06-01 08:42:31
...
递归实现:
#include<iostream>
using namespace std;
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;
}
swap(pRoot->left,pRoot->right);
Mirror(pRoot->right);
Mirror(pRoot->left);
}
};
非递归实现:
/*
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;
}
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty())
{
TreeNode *per = q.front();
TreeNode *tmp = per->left;
per->left = per->right;
per->right = tmp;
if(per->right!=NULL)
{
q.push(per->right);
}
if(per->left!=NULL)
{
q.push(per->left);
}
}
q.pop();
}
};
下一篇: 二叉树的镜像