[Careercup] 13.7 node Pointer pointer

Source: Internet
Author: User

13.7 Write A method, takes a pointer to a NODE structure as a parameter and returns a complete copy of the passed in D ATA structure. The Node data structure contains the pointers to other Nodes.

In this question let us copy the entire data structure through a node pointer, node class nodes contains two node pointers, we need to use a hash table to establish the original data structure of each node address to the corresponding new structure of the address, so that we can use DFS when we know which nodes we have copied, You can skip it directly. In this way, it is possible to mark the nodes that have been accessed without storing them inside the node. The copy process is as follows:

classNode { Public: Node*ptr1; Node*ptr2;}; typedef unordered_map<node*, node*>Nodemap;classSolution { Public: Node* Copy_structure (Node *root)        {Nodemap m; returncopy_recursive (Root, M); } Node* Copy_recursive (Node *cur, Nodemap &m) {if(cur = = nullptr)returnnullptr; Auto It=m.find (cur); if(It! = M.end ())returnIt->second; Node*node =NewNode; M[cur]=node; Node-&GT;PTR1 = Copy_recursive (cur->ptr1, M); Node-&GT;PTR2 = Copy_recursive (cur->ptr2, M); returnnode; }};

[Careercup] 13.7 node Pointer pointer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.