Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created November 24, 2023 21:05
Show Gist options
  • Select an option

  • Save primaryobjects/7239e226cdbff045c07a7a2bdad88c6d to your computer and use it in GitHub Desktop.

Select an option

Save primaryobjects/7239e226cdbff045c07a7a2bdad88c6d to your computer and use it in GitHub Desktop.
Find a Corresponding Node of a Binary Tree in a Clone of That Tree https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} original
* @param {TreeNode} cloned
* @param {TreeNode} target
* @return {TreeNode}
*/
const getTargetCopy = function(original, cloned, target) {
// Walk through cloned tree until we reach target value, using depth first search.
const val = target.val;
let fringe = [cloned];
let head = fringe.pop();
while (head) {
if (head.val === val) {
// We're done.
break;
}
else {
// Go deeper left and right.
head.left && fringe.push(head.left);
head.right && fringe.push(head.right);
}
head = fringe.pop(); // stack
}
return head;
};
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment