Leetcode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Given two binary trees original
and cloned
and a reference to a node target
in the original tree, you need to find the node in the cloned tree that corresponds to the target
node in the original tree.
Both trees are identical versions of each other, and cloned is a copy of the original tree.
nullptr
?
We will perform a Depth-First Search (DFS) on both trees simultaneously. While traversing both trees together, we will check if the node in the original tree matches the target node. When we find the node in the original tree that matches the target, we return the corresponding node in the cloned tree.
Steps:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
if (original == nullptr) return nullptr;
if (original == target) return cloned;
TreeNode* leftResult = getTargetCopy(original->left, cloned->left, target);
if (leftResult != nullptr) return leftResult;
return getTargetCopy(original->right, cloned->right, target);
}
};
The time complexity of this algorithm is (O(N)), where (N) is the number of nodes in the tree. This is because we may potentially need to visit all nodes in the tree to find the target node.
The space complexity of the algorithm is (O(H)), where (H) is the height of the tree, considering the auxiliary stack space used by the recursion. In the worst case, for a completely unbalanced tree, (H) can be (N). For a balanced tree, (H) will be (O(\log N)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?