LeetCode 筆記 - 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

題目在此 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

給兩個 Binary Tree 一棵樹是另一顆的複製,還有 target node
請回傳 target node 在複製樹上的 reference

解題思維

很單純就是 Tree traversal
跑完一次就解決了

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:

def search(root):
if not root:
return None
if root.val == target.val:
return root

if result := search(root.left):
return result
if result := search(root.right):
return result

return None

if not original:
return None

return search(cloned)

也許你也會想看看