Leetcode 1379.找出克隆二叉樹中的相同節點(Find a Corresponding Node of a Binary Tree in a Clone of That Tree)

Leetcode 1379.找出克隆二叉樹中的相同節點

1 題目描述(Leetcode題目鏈接

  給你兩棵二叉樹,原始樹 original 和克隆樹 cloned,以及一個位於原始樹 original 中的目標節點 target。

其中,克隆樹 cloned 是原始樹 original 的一個 副本 。

請找出在樹 cloned 中,與 target 相同 的節點,並返回對該節點的引用(在 C/C++ 等有指針的語言中返回 節點指針,其他語言返回節點本身)。
注意:

  • 你 不能 對兩棵二叉樹,以及 target 節點進行更改。
  • 只能 返回對克隆樹 cloned 中已有的節點的引用。

進階:如果樹中允許出現值相同的節點,你將如何解答?

在這裏插入圖片描述

輸入: tree = [7,4,3,null,null,6,19], target = 3
輸出: 3
解釋: 上圖畫出了樹 original 和 cloned。target 節點在樹 original 中,用綠色標記。答案是樹 cloned 中的黃顏色的節點(其他示例類似)。

提示:

  • 樹中節點的數量範圍爲 [1, 10^4] 。
  • 同一棵樹中,沒有值相同的節點。
  • target 節點是樹 original 中的一個節點,並且不會是 null 。

2 題解

  在cloned裏面找到與target值相同的節點就可以了,因此只需要遍歷樹就好了。對於進階,如果出現相同的值,就需要根據原樹判斷。

# 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:
        stack = []
        while cloned or stack:
            while cloned:
                stack.append(cloned)
                cloned = cloned.left
            cloned = stack.pop()
            if cloned.val == target.val:
                return cloned
            cloned = cloned.right
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章