Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Desolve/af0e4cf14db21baf15da0e10aa9b4121 to your computer and use it in GitHub Desktop.
Save Desolve/af0e4cf14db21baf15da0e10aa9b4121 to your computer and use it in GitHub Desktop.
1379 Find a Corresponding Node of a Binary Tree in a Clone of That Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public final TreeNode helper(final TreeNode n, final int v) {
if (n == null) return null;
if (n.val == v) return n;
TreeNode l = helper(n.left, v);
if (l != null) return l;
TreeNode r = helper(n.right, v);
if (r != null) return r;
return null;
}
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
int v = target.val;
return helper(cloned, v);
}
}
/* Solution from leetcode
class Solution {
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
if( original == null ) return cloned;
return dfs( original, cloned, target );
}
public TreeNode dfs( final TreeNode original, final TreeNode cloned, final TreeNode target ) {
if( original == target ) return cloned;
if( original.left != null ) {
TreeNode tmp = dfs( original.left, cloned.left, target );
if( tmp != null ) return tmp;
}
if( original.right != null ) {
TreeNode tmp = dfs( original.right, cloned.right, target );
if( tmp != null ) return tmp;
}
return null;
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment