[LeetCode] Find a Corresponding Node of a Binary Tree in a Clone of That Tree

1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Given two binary trees original and cloned and given a reference to a node target in the original tree.

The cloned tree is a copy of the original tree.

Return a reference to the same node in the cloned tree.

Note that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
TreeNode* helper(TreeNode* o, TreeNode* t, TreeNode* c) {
if(!o) return NULL;
if(o == t) return c;
auto l = helper(o->left, t, c->left);
if(l != NULL) return l;
return helper(o->right, t, c->right);
}
public:
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
if(!target) return NULL;
return helper(original, target, cloned);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/LeetCode/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.