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

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

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) —

推荐阅读:
红薯怎么吃润肠通便及红薯食用禁忌  吃海带的十大好处和海带的饮食禁忌  经常食用这三种饭有助于预防肠癌  保健食品需谨慎 所谓效果是心理作用  关于预防癌症的十条饮食和生活建议  春季喝蜂蜜功效胜补品抗过敏润肺止咳  这十种食用方法让蜂蜜营养又健康  婴幼儿等四类人群不宜食用蜂蜜  教你这七招快速辨别蜂蜜的真假  舌尖上的中国之虾子面背后的故事 
评论列表
添加评论