# 1485. Clone Binary Tree With Random Pointer

[1485. Clone Binary Tree With Random Pointer](https://leetcode.com/problems/clone-binary-tree-with-random-pointer/)

概念和 [138. Copy List with Random Pointer](/algorithm-and-data-structure/classic-problems/clone-graph/copy-list-with-random-pointer.md) 一模一樣。

```python
# Definition for Node.
# class Node:
#     def __init__(self, val=0, left=None, right=None, random=None):
#         self.val = val
#         self.left = left
#         self.right = right
#         self.random = random

class Solution:
    def copyRandomBinaryTree(self, root: 'Node') -> 'NodeCopy':
        if not root:
            return None
        table = {}
        copy = NodeCopy(root.val)
        table[root] = copy

        queue = deque([(root, copy)])
        while queue:
            node, copy_node = queue.popleft()
            if node.left:
                copy_node.left = NodeCopy(node.left.val)
                table[node.left] = copy_node.left
                queue.append((node.left, copy_node.left))
            if node.right:
                copy_node.right = NodeCopy(node.right.val)
                table[node.right] = copy_node.right
                queue.append((node.right, copy_node.right))

        queue = deque([root])

        while queue:
            node = queue.popleft()
            if node.random:
                random = table[node.random]
                table[node].random = random
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        return table[root]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://garylai.gitbook.io/algorithm-and-data-structure/classic-problems/clone-graph/clone-binary-tree-with-random-pointer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
