Clone (Deep Copy) Binary Tree With Random Pointer using Hash Map

  • 时间:2020-09-08 11:19:41
  • 分类:网络文摘
  • 阅读:160 次

A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null. Return a deep copy of the tree.

The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (in the input) where the random pointer points to, or null if it does not point to any node.

You will be given the tree in class Node and you should return the cloned tree in class NodeCopy. NodeCopy class is just a clone of Node class with the same attributes and constructors.

Example 1, 2 and 3: Deep Copy Binary Tree with Random Pointer

clone-binary-tree-with-random-pointer-scaled Clone (Deep Copy) Binary Tree With Random Pointer using Hash Map and Recursion algorithms c / c++ DFS recursive

clone-binary-tree-with-random-pointer

Example 1:
Input: root = [[1,null],null,[4,3],[7,0]]
Output: [[1,null],null,[4,3],[7,0]]
Explanation: The original binary tree is [1,null,4,7].
The random pointer of node one is null, so it is represented as [1, null].
The random pointer of node 4 is node 7, so it is represented as [4, 3] where 3 is the index of node 7 in the array representing the tree.
The random pointer of node 7 is node 1, so it is represented as [7, 0] where 0 is the index of node 1 in the array representing the tree.

Example 2:
Input: root = [[1,4],null,[1,0],null,[1,5],[1,5]]
Output: [[1,4],null,[1,0],null,[1,5],[1,5]]
Explanation: The random pointer of a node can be the node itself.

Example 3:
Input: root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
Output: [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]

Example 4:
Input: root = []
Output: []

Example 5:
Input: root = [[1,null],null,[2,null],null,[1,null]]
Output: [[1,null],null,[2,null],null,[1,null]]

Constraints:
The number of nodes in the tree is in the range [0, 1000].
Each node’s value is between [1, 10^6].

Hints:
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree.
Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.

Recursive Deep Copy of Binary Tree with Hash Map

We can recursive copy the attributes/properties of the binary tree. Since the random pointers may cause endless loop (cycles), we need to use a hash map to remember the nodes that we always clone.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     Node *left;
 *     Node *right;
 *     Node *random;
 *     Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {}
 *     Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {}
 *     Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {}
 * };
 */
class Solution {
public:
    NodeCopy* copyRandomBinaryTree(Node* root) {
        if (!root) return NULL;
        if (memo.find(root) != memo.end()) {
            return memo[root];
        }
        NodeCopy* newRoot = new NodeCopy();
        memo[root] = newRoot;
        newRoot->val = root->val;
        newRoot->left = copyRandomBinaryTree(root->left);
        newRoot->right = copyRandomBinaryTree(root->right);    
        newRoot->random = copyRandomBinaryTree(root->random);            
        return newRoot;
    }
private:
    unordered_map<Node*, NodeCopy*> memo;
};
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     Node *left;
 *     Node *right;
 *     Node *random;
 *     Node() : val(0), left(nullptr), right(nullptr), random(nullptr) {}
 *     Node(int x) : val(x), left(nullptr), right(nullptr), random(nullptr) {}
 *     Node(int x, Node *left, Node *right, Node *random) : val(x), left(left), right(right), random(random) {}
 * };
 */
class Solution {
public:
    NodeCopy* copyRandomBinaryTree(Node* root) {
        if (!root) return NULL;
        if (memo.find(root) != memo.end()) {
            return memo[root];
        }
        NodeCopy* newRoot = new NodeCopy();
        memo[root] = newRoot;
        newRoot->val = root->val;
        newRoot->left = copyRandomBinaryTree(root->left);
        newRoot->right = copyRandomBinaryTree(root->right);    
        newRoot->random = copyRandomBinaryTree(root->random);            
        return newRoot;
    }
private:
    unordered_map<Node*, NodeCopy*> memo;
};

When we immediately create a clone node, we need to put it in hash map before recursively calling deep-copy function to clone the left, right, and the random pointers. The sequence matters otherwise a stackoverflow will occur due to endless cycles.

Similarly, we can apply such algorithm to clone a graph: How to Clone a Graph in C++/Java using Depth First Search Algorithm? (Graph and HashMap)

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
白蛇传说大吐糟。。。白蛇传说里的句子语录  调研随想  读《心灵无草》有感 作文1200字  那扇门永远为你敞开作文450字  都是马虎惹的祸作文700字  写人作文我们的周老师作文400字  雨水和想念  医生手上的苍蝇作文600字  What You Need if You Want to Be a Freelancer  Best Ways to Maximize the Speed ​​& Performance of Your Word 
评论列表
添加评论