'merging 2 binary trees- Easy
I am trying to merge 2 binary trees, without worrying about making the resultant tree balanced. Here is my solution which does not work. Why are the Treenode ans and head set to 0 when they come back from merge functions. as i understand since TreeNode is not primitive type, head which points to ans should be updated with the resultant tree after call to merge function https://leetcode.com/problems/merge-two-binary-trees/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
TreeNode ans = new TreeNode();
TreeNode head = ans;
if(root1!=null && root2==null)
return root1;
else if (root1==null && root2!=null)
return root2;
else if (root1!=null &&root2!=null)
merge (root1, root2,ans) ;
return head;
}
void merge (TreeNode root1, TreeNode root2,TreeNode ans)
{
if(root1!=null && root2==null)
root2 = new TreeNode(0);
else if (root1==null && root2!=null)
root1 = new TreeNode(0);
else if(root1==null &&root2==null)
return;
ans = new TreeNode(root1.val+root2.val);
merge(root1.left,root2.left,ans.left);
merge(root1.right,root2.right,ans.right);
}
}
Solution 1:[1]
The problem is that the variables head
and ans
are not going to be updated like you expect them to. Java is pass-by-value as explained here. This means that ans
is a reference that you're passing the value of to the function merge
and then overwriting over there.
You are also re-assigning the value of ans
with every recursive call of merge
. To return the correct value you would need to return the value assigned to that variable on the very first call.
Hope this is helpful.
Solution 2:[2]
Java passes references by value. Inside the method if you change the value of an attribute of the object that will work. But if you assign the pointer to a new object it will not chnage the original object
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | abdurrhman el shimy |
Solution 2 |