我试图获取二叉树的镜像,但是由于对指针的了解较少,我很难调试代码。可以帮助我调试代码......
算法:
然后在弹出前节点时创建镜像树
我在做什么?
答案 0 :(得分:1)
我已经更正了代码。请查看是否有帮助
#include<bits/stdc++.h>
using namespace std;
struct treenode{
int data;
struct treenode* left , *right;
};
struct treenode* createNode(int data)
{
struct treenode* node = (struct treenode*)malloc(sizeof(struct treenode));
node->data = data;
node->right = NULL;
node->left = NULL;
return node;
}
//Function for inserting node for creating mirror of binary tree
void insert(struct treenode **root2,int data)
{
struct treenode* temp;
if(*root2 == NULL)
{
*root2 = createNode(data);
return;
}
else{
queue<treenode*> q;
q.push(*root2);
while(!q.empty())
{
temp = q.front();
q.pop();
if(temp->left)
q.push(temp->left);
else{
temp->left = createNode(data);
return;
}
if(temp->right)
{
q.push(temp->right);
}
else{
temp -> right = createNode(data);
return;
}
}
}
}
void mirror(struct treenode* node)
{
if (node==NULL)
return;
else
{
struct treenode* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
//For printing the tree
void level_order(struct treenode** root)
{
if(root==NULL) return;
queue<treenode*> q;
q.push(*root);
while(!q.empty())
{
struct treenode* temp = q.front();
q.pop();
cout << temp->data << " ";
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
//Driver Function
int main()
{
struct treenode* root2 = NULL;
struct treenode* root = createNode(1);
root->left = createNode(3);
root->right = createNode(2);
root->right->left = createNode(5);
root->right->right = createNode(4);
level_order(&root);
mirror(root);
printf("\n");
level_order(&root);
return 0;
}
输出:
1 3 2 5 4
1 2 3 4 5
答案 1 :(得分:0)
//Function for creating Binary Tree
//Assuming *root for original tree and *root2 for mirror tree
//are declared globally
void insert(int data)
{
struct treenode* temp;
if(root2 == NULL)
{
root2 = createNode(data);
return;
}
else{
queue<treenode*> q;
q.push(root2);
while(!q.empty())
{
temp = q.front();
q.pop();
if(temp->left)
q.push(temp->left);
else{
temp->left = createNode(data);
return;
}
if(temp->right)
{
q.push(temp->right);
}
else{
temp -> right = createNode(data);
return;
}
}
}
}
//Iterative version for Mirror of a Binary Tree
void mirrorBinaryTree()
{
struct treenode *front;
queue<treenode*> q;
q.push(root);
while(!q.empty())
{
front = q.front();
insert(front->data);
q.pop();
if(front->right)
q.push(front->right);
if(front->left)
q.push(front->left);
}
}
答案 2 :(得分:0)
我认为如果你递归编码会更容易。一些如:
Node * mirror(Node * root)
{
if (root == nullptr)
return nullptr;
Node * r = new Node; // here we will copy the root
r->key = root->key; // or whatever the root contains
r->left = mirror(root->right);
r->right = mirror(root->left);
return r;
}