tags:

views:

60

answers:

2

The code I wrote so far is:

void copyInOrder(TNode *orgTree, Tnode *& copyTree){
    if(orgTree !=NULL){
        copyInOrder(orgTree->left_link);
        //create leftmost node of tree but how to link to parent
        copyInOrder(orgTree->right_link);
    }
}

I dont know how to link to the parent to the nodes as its inorder.

+1  A: 

I think it would be something like this.

void copyInOrder(TNode *orgTree, Tnode *& copyTree){
    if(orgTree !=NULL){
        //left side
        TNode newLeftNode = cloneNode(orgTree->left_link);
        copyTree->left_link = newLeftNode;
        copyInOrder(orgTree->left_link, copyTree->left_link);

        //right side
        TNode newRightNode = cloneNode(orgTree->right_link);
        copyTree->right_link = newRightNode;
        copyInOrder(orgTree->right_link, copyTree->right_link);
    }
}
Alpha
where is the definition of cloneNode?
@user432495 I didn't write it, but it would be a method that created a new node based on the data from another one.
Alpha
+1  A: 

Suppose orgTree points to root (2). For copying, we have to do the following:

alt text

  1. create a node at copyTree, and the copy the value 2 into it
  2. if orgTree->left != NULL, call copyInOrder( orgTree->left, copyTree->left );
  3. if orgTree->right != NULL, call copyInOrder( orgTree->right, copyTree->right );

BTW, this type of traversal is known as pre-order traversal, in-order traversal is different.

ArunSaha