240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 19 | Leetcode 1490. Clone N-ary Tree

题解

Medium

BFS

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    Node* cloneTree(Node* root) {
        if(!root) return nullptr;
        
        Node* copy = new Node(root->val);
        
        unordered_map<Node*, Node*> m;
        m[root] = copy;
        
        queue<Node*> q;
        q.push(root);
        
        while(!q.empty()) {
            Node* n = q.front();
            q.pop();

            for(Node* next : n->children) {
                if(!m.count(next)) {
                    q.push(next);
                    copy = new Node(next->val);
                    m[next] = copy;
                    m[n]->children.push_back(copy);
                }
            }
        }
        
        return m[root];
    }
};
posted @ 2020-10-06 13:21  CasperWin  阅读(156)  评论(0编辑  收藏  举报