leetcode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree(在BT的copy中找到对应的节点)

Given two binary trees original and cloned and given a reference to a node target in the original tree.

The cloned tree is a copy of the original tree.

Return a reference to the same node in the cloned tree.

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 node in the cloned tree.

Example 1:
在这里插入图片描述
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.

Constraints:

The number of nodes in the tree is in the range [1, 104].
The values of the nodes of the tree are unique.
target node is a node from the original tree and is not null.

有两个二叉树(注意不是二叉搜索树)original 和 cloned, cloned就是original的copy, 在clone中找到target节点。

思路:
始终不知道这道题中original这棵树有什么作用,觉得是个冗余信息。
既然cloned是original的copy, 那么值肯定都是一样的,
而且树的值都是unique的,那么target节点一定唯一,
直接在cloned树中搜索值就好了。

注意因为不是二叉搜索树,所以左右子树都要搜索。

class Solution {
    TreeNode res;
    public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
        find(cloned, target);
        return res;
    }
    
    boolean find(TreeNode root, TreeNode target) {
        if(root == null) return false;
        
        if(root.val == target.val) {
            res = root;
            return true;
        };
        
        if(find(root.left, target)) return true;
        
        if(find(root.right, target)) return true;
        
        return false;
    }
}

当然标准解法还是original 和 cloned 一起遍历,在找到了original的节点后,返回对应的cloned节点。

    public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
        if(original == null) return null;
        
        if(original == target) return cloned;
        
        TreeNode left = getTargetCopy(original.left, cloned.left, target);
        if(left == null) return getTargetCopy(original.right, cloned.right, target);
        
        return left;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值