|
| 1 | +""" |
| 2 | +MEDIUM |
| 3 | +1379. [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) |
| 4 | +
|
| 5 | +Given two binary trees original and cloned and given a reference to a node target in the original tree. |
| 6 | +
|
| 7 | +The cloned tree is a copy of the original tree. |
| 8 | +
|
| 9 | +Return a reference to the same node in the cloned tree. |
| 10 | +
|
| 11 | +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 |
| 12 | +node in the cloned tree. |
| 13 | +
|
| 14 | +Follow up: Solve the problem if repeated values on the tree are allowed. |
| 15 | +
|
| 16 | +Example 1: |
| 17 | +Input: tree = [7,4,3,null,null,6,19], target = 3 |
| 18 | +Output: 3 |
| 19 | +Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original |
| 20 | +tree. The answer is the yellow node from the cloned tree. |
| 21 | +
|
| 22 | +Example 2: |
| 23 | +Input: tree = [7], target = 7 |
| 24 | +Output: 7 |
| 25 | +
|
| 26 | +Example 3: |
| 27 | +Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4 |
| 28 | +Output: 4 |
| 29 | +
|
| 30 | +Example 4: |
| 31 | +Input: tree = [1,2,3,4,5,6,7,8,9,10], target = 5 |
| 32 | +Output: 5 |
| 33 | +
|
| 34 | +Example 5: |
| 35 | +Input: tree = [1,2,null,3], target = 2 |
| 36 | +Output: 2 |
| 37 | +
|
| 38 | +Constraints: |
| 39 | +The number of nodes in the tree is in the range [1, 10^4]. |
| 40 | +The values of the nodes of the tree are unique. |
| 41 | +target node is a node from the original tree and is not null. |
| 42 | +""" |
| 43 | + |
| 44 | + |
| 45 | +# Definition for a binary tree node. |
| 46 | +# class TreeNode: |
| 47 | +# def __init__(self, x): |
| 48 | +# self.val = x |
| 49 | +# self.left = None |
| 50 | +# self.right = None |
| 51 | + |
| 52 | + |
| 53 | +class Solution: |
| 54 | + def getTargetCopy( |
| 55 | + self, original: TreeNode, cloned: TreeNode, target: TreeNode |
| 56 | + ) -> TreeNode: |
| 57 | + def inorder(root, target): |
| 58 | + stack = [] |
| 59 | + while root is not None or len(stack) > 0: |
| 60 | + while root is not None: |
| 61 | + stack.append(root) |
| 62 | + root = root.left |
| 63 | + root = stack.pop() |
| 64 | + if root.val == target.val: |
| 65 | + return root |
| 66 | + root = root.right |
| 67 | + return |
| 68 | + |
| 69 | + return inorder(cloned, target) |
| 70 | + |
| 71 | + |
| 72 | +# Runtime : 612 ms, faster than 83.77% of Python3 online submissions |
| 73 | +# Memory Usage : 24.1 MB, less than 43.70% of Python3 online submissions |
0 commit comments