Copy binary tree in order
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 l开发者_StackOverflowink to parent
copyInOrder(orgTree->right_link);
}
}
I dont know how to link to the parent to the nodes as its inorder.
Suppose orgTree
points to root (2
). For copying, we have to do the following:
- create a node at
copyTree
, and the copy the value 2 into it - if
orgTree->left != NULL
, callcopyInOrder( orgTree->left, copyTree->left );
- if
orgTree->right != NULL
, callcopyInOrder( orgTree->right, copyTree->right );
BTW, this type of traversal is known as pre-order traversal, in-order traversal is different.
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);
}
}
tnode *copy(tnode *root) {
tnode *new_root;
if(root!=NULL){
new_root=new tnode;
new_root->data=root->data;
new_root->lchild=copy(root->lchild);
new_root->rchild=copy(root->rchild);
} else return NULL;
return new_root;
}
This is a recursive method that works and is simple
Tnode* CopyInOrder(Tnode* root){
if(root == NULL){return NULL;}
else{
Tnode* temp = new Tnode;
temp -> data = root -> data;
temp -> left = copyInOrder(root -> left);
temp -> right = copyInOrder(root -> right);
return temp;
}
}
I am not authorized to flag or comment. Maybe someone who is authorized will take action on the hijacked link. And then, maybe delete my post (this post) since it will no longer be relevant.
Referring to the post of Oct 12 '10 at 21:02 by Arun:
I inspected the link (i.e., right-click, then click on "inspect"). The URL looks legitimate. However, when I actually click on the link, I get redirected to a completely different URL of a website that wants to download and install a plugin. Norton Security blocks the website. To me, it looks like the original link was hijacked.
The original post shows knowledge and helpfulness.
For safety, maybe we should change to google the search term "pre-order traversal."
精彩评论