Solved

# Interchange

Posted on 1999-12-22
Medium Priority
353 Views

How would I write a function in c++ that will interchange all left and right subtrees in a linked binary tree.
1                                                            1
/  \                                                          /  \
2   3                becomes -->                    3     2
/    / \                                                    /  \     \
4    5   6                                                 6    5     4
/ \                                                         /  \
7  8                                                       8   7

I don't need the entire program, just the required function segment of code.

the definition of the tree node I have is:

typedef struct treenode
{
int data;
struct treenode *left;
struct treenode *right;
}TreeNode;

typedef TreeNode *TreePointer;

And I was given this answer:
void InterChange(TreeNode *tN)
{
TreeNode *left =  tN->left; //get left node
TreeNode *right =  tN->right; //grt right node
if (left || right) //not last?
{
tN->left = right; //left = write
tN->right = left; //righ =left
if (tN->left) //exist left?
InterChange(tN->left); //make interchange inside                                                  // left(recursion)
if (tN->right) //exist right?
InterChange(tN->right); //make interchange inside                                                    //right(recursion)
}
}

So the typedef TreeNode *TreePointer; after the structure is not needed or used in the InterChange function??
0
Question by:tlounsbu
• 3
• 2

LVL 2

Accepted Solution

arikka earned 50 total points
ID: 2301046
You do not need TreePointer type
Do not use it in the elegant
InterChange(TreeNode *tN)as well.

0

Author Comment

ID: 2301154
So, the typedef TreeNode *TreePointer; line of code would not be needed in order for the function InterChange to work correctly in order to interchange the tree.
0

LVL 2

Expert Comment

ID: 2301168
Absolutely
0

Author Comment

ID: 2301238
Is the function InterChange correct then? Would it interchange the tree as it is coded above with the structure?
0

Author Comment

ID: 2338801
As it ends up, this code doesn't do what I was expecting it to at all.
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.