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;
}