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

本文探討如何在複製的二元樹中找出對應目標節點的參照。這是一個典型的樹遍歷問題,透過同步探索原始樹與複製樹,能快速定位目標。本文提供基礎的 Tree Traversal 實作思路,幫助讀者掌握遞迴搜尋技巧。

發佈
閱讀
約 1 分鐘
字數
225
⚠️ 舊文提醒:本文發佈於約 4 年前,部分內容或指令可能已過時,請斟酌參考。

題目在此 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)

也許你也會想看看

輸入關鍵字開始搜尋 · ↑↓ 選擇 · Enter 開啟