DEV Community

Nic
Nic

Posted on • Originally published at coderscat.com on

LeetCode: Clone Binary Tree With Random Pointer

CAPTURE-2020_07_15_clone-binary-tree-with-random-pointer.org_20200715_113620.png

Deep copy

Deep copy is a process in which the copying process occurs recursively. We need to clone all the elements of a tree.

Solution

The overall algorithm is recursive, but we need to find the previous cloned elements. So use a hashmap will help us to store the pair relationship of the elements of source tree and the new cloned elements.

class Solution {
public:
    map<Node*, NodeCopy*> node_map;

    NodeCopy* copyRandomBinaryTree(Node* root) {
        if(root == NULL) return NULL;
        return dfs(root);
    }

    NodeCopy* dfs(Node* cur) {
        if(cur == NULL) return NULL;
        if(node_map.count(cur))
            return node_map[cur];
        NodeCopy* node = new NodeCopy(cur->val);
        node_map[cur] = node;
        node->left = dfs(cur->left);
        node->right = dfs(cur->right);
        node->random = dfs(cur->random);
        return node;
    }
};

Enter fullscreen mode Exit fullscreen mode

The post LeetCode: Clone Binary Tree With Random Pointer appeared first on Coder's Cat.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more