Skip to content

Commit d86d83a

Browse files
committed
feat: add more
1 parent ff82e36 commit d86d83a

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

Tree/ModelDefinition/Tree.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export class TreeNode {
2+
val: number
3+
left: TreeNode | null
4+
right: TreeNode | null
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val
7+
this.left = left === undefined ? null : left
8+
this.right = right === undefined ? null : right
9+
}
10+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
// ![](https://assets.leetcode.com/uploads/2020/02/21/e1.png)
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+
// ![](https://assets.leetcode.com/uploads/2020/02/21/e2.png)
23+
// ```
24+
// **Input:** tree = [7], target = 7
25+
// **Output:** 7
26+
// ```
27+
//
28+
// **Example 3:**
29+
//
30+
// ![](https://assets.leetcode.com/uploads/2020/02/21/e3.png)
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

Comments
 (0)