2 January 2021
LeetCode(1379) -- Find a Corresponding Node of a Binary Tree in a Clone of That Tree
by Jerry Zhang
Problem
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.
Follow up: Solve the problem if repeated values on the tree are allowed.
My Solution
同时遍历两棵树,当一棵树找到target时,另一棵树也就找到了ans。
class Solution {
TreeNode target, ans;
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
this.target = target;
dfs(original, cloned);
return this.ans;
}
private void dfs(final TreeNode original, final TreeNode cloned) {
if (original == null) {
return;
}
dfs(original.left, cloned.left);
if (original == target) {
ans = cloned;
return;
}
dfs(original.right, cloned.right);
}
}