当前位置:网站首页>【二叉树-中等】1379. 找出克隆二叉树中的相同节点

【二叉树-中等】1379. 找出克隆二叉树中的相同节点

2022-08-10 01:52:00 菜菜2022

【题目】
【代码】
【方法1】这个是大多数人的解法,其实是不对的,虽然结果正确
在这里插入图片描述

# 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:
        ans=None
        def dfs(root):
            nonlocal ans
            if not root:
                return 
            if root.val==target.val and ans==None:
                ans=root
            dfs(root.left)
            dfs(root.right)
        dfs(cloned)
        return ans

【方法2】正确解法
在这里插入图片描述

# 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:
        if not original:
            return None
        if original==target: return cloned
        left=self.getTargetCopy(original.left,cloned.left,target)
        if left:return left
        return self.getTargetCopy(original.right,cloned.right,target)
原网站

版权声明
本文为[菜菜2022]所创,转载请带上原文链接,感谢
https://blog.csdn.net/kz_java/article/details/126224370