Can someone tell me why the console.log outputs the right answer, however, the return outputs null?
I am trying to traverse two identical trees, and then when a target value is found in a node in the original tree, I am trying to return the same node value in the cloned tree.
I really appreciate any help you can provide.
Original problem: https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
Codebase:
var getTargetCopy = function(original, cloned, target) {
if(original === null) {
return null
}
original.left = getTargetCopy(original.left, cloned.left, target)
original.right = getTargetCopy(original.right, cloned.right, target)
if(original.val === target.val) {
console.log(cloned.val)
return cloned.val
}
};
Inputs:
Your input:
original = [7,4,3,null,null,6,19]
cloned = [7,4,3,null,null,6,19]
target.val = 3
Console.log:
stdout:
3
Outputs:
Output:
null
Desired answer:
Expected:
3
Some issues:
The function is supposed to return a node, not a value, so return cloned.val
is wrong. It should be return cloned
With the following statements you are mutating the original tree:
original.left = getTargetCopy(original.left, cloned.left, target) original.right = getTargetCopy(original.right, cloned.right, target)
That should not happen.
with if(original.val === target.val)
your code could have a false positive when target.val
is not a unique value. Instead you should compare the node reference .
When you have a match, you should not have to recurse deeper, so perform this test before doing the recursive calls.
When a recursive call returns a node, you should immediately return that node and not do any other recursive call.
Here is your code corrected:
var getTargetCopy = function(original, cloned, target) {
if(original === null) {
return null
}
if(original === target) {
return cloned;
}
return getTargetCopy(original.left, cloned.left, target)
|| getTargetCopy(original.right, cloned.right, target)
};
Making it a bit more condensed, it can be:
var getTargetCopy = (original, cloned, target) =>
!original || original === target
? cloned
: getTargetCopy(original.left, cloned.left, target)
|| getTargetCopy(original.right, cloned.right, target);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.