-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path1485-CloneBinaryTreeWithRandomPointer.cs
81 lines (71 loc) · 2.37 KB
/
1485-CloneBinaryTreeWithRandomPointer.cs
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//-----------------------------------------------------------------------------
// Runtime: 252ms
// Memory Usage: 45.3 MB
// Link: https://leetcode.com/submissions/detail/360429492/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
/**
* Definition for Node.
* public class Node {
* public int val;
* public Node left;
* public Node right;
* public Node random;
* public Node(int val=0, Node left=null, Node right=null, Node random=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* this.random = random;
* }
* }
*/
public class _1485_CloneBinaryTreeWithRandomPointer
{
public NodeCopy CopyRandomBinaryTree(Node root)
{
var map = new Dictionary<Node, NodeCopy>();
return CopyRandomBinaryTree(root, map);
}
private NodeCopy CopyRandomBinaryTree(Node node, Dictionary<Node, NodeCopy> map)
{
if (node == null) return null;
if (map.ContainsKey(node)) return map[node];
var newNode = new NodeCopy(node.val);
map.Add(node, newNode);
newNode.left = CopyRandomBinaryTree(node.left, map);
newNode.right = CopyRandomBinaryTree(node.right, map);
newNode.random = CopyRandomBinaryTree(node.random, map);
return newNode;
}
public class Node
{
public int val;
public Node left;
public Node right;
public Node random;
public Node(int val = 0, Node left = null, Node right = null, Node random = null)
{
this.val = val;
this.left = left;
this.right = right;
this.random = random;
}
}
public class NodeCopy
{
public int val;
public NodeCopy left;
public NodeCopy right;
public NodeCopy random;
public NodeCopy(int val = 0, NodeCopy left = null, NodeCopy right = null, NodeCopy random = null)
{
this.val = val;
this.left = left;
this.right = right;
this.random = random;
}
}
}
}