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