|
| 1 | +// https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree |
| 2 | +// |
| 3 | +// Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. |
| 4 | +// |
| 5 | +// The `cloned` tree is a **copy of** the `original` tree. |
| 6 | +// |
| 7 | +// Return _a reference to the same node_ in the `cloned` tree. |
| 8 | +// |
| 9 | +// **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. |
| 10 | +// |
| 11 | +// **Example 1:** |
| 12 | +// |
| 13 | +//  |
| 14 | +// ``` |
| 15 | +// **Input:** tree = [7,4,3,null,null,6,19], target = 3 |
| 16 | +// **Output:** 3 |
| 17 | +// **Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree. |
| 18 | +// ``` |
| 19 | +// |
| 20 | +// **Example 2:** |
| 21 | +// |
| 22 | +//  |
| 23 | +// ``` |
| 24 | +// **Input:** tree = [7], target = 7 |
| 25 | +// **Output:** 7 |
| 26 | +// ``` |
| 27 | +// |
| 28 | +// **Example 3:** |
| 29 | +// |
| 30 | +//  |
| 31 | +// ``` |
| 32 | +// **Input:** tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4 |
| 33 | +// **Output:** 4 |
| 34 | +// ``` |
| 35 | +// |
| 36 | +// **Constraints:** |
| 37 | +// |
| 38 | +// * The number of nodes in the `tree` is in the range `[1, 10<sup>4</sup>]`. |
| 39 | +// * The values of the nodes of the `tree` are unique. |
| 40 | +// * `target` node is a node from the `original` tree and is not `null`. |
| 41 | +// |
| 42 | +// **Follow up:** Could you solve the problem if repeated values on the tree are allowed? |
| 43 | + |
| 44 | +import { TreeNode } from './ModelDefinition/Tree' |
| 45 | + |
| 46 | +function getTargetCopy( |
| 47 | + original: TreeNode | null, |
| 48 | + cloned: TreeNode | null, |
| 49 | + target: TreeNode | null, |
| 50 | +): TreeNode | null { |
| 51 | + if (!original || !cloned || !target) return null |
| 52 | + if (original === target) return cloned |
| 53 | + return ( |
| 54 | + getTargetCopy(original.left, cloned.left, target) || |
| 55 | + getTargetCopy(original.right, cloned.right, target) |
| 56 | + ) |
| 57 | +} |
0 commit comments