Could anyone help me where my code is wrong?


  • 0
    X

    I am new to java, and do not know why my code always returns -1. Appreciate is anyone can help, thanks.
    public class Solution {
    private TreeNode root=new TreeNode(-1);
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
    help(t1, t2, root);
    return root;
    }

    public void help(TreeNode t1, TreeNode t2, TreeNode t){
        if(t1!=null&&t2!=null){
             t=new TreeNode(t1.val+t2.val);
             help(t1.left, t2.left, t.left);
             help(t1.right, t2.right, t.right);
        }
        else if(t1!=null&&t2==null){
             t=new TreeNode(t1.val);
             help(t1.left, null, t.left);
             help(t1.right, null, t.right);
        }
        else if(t2!=null&&t1==null){
             t=new TreeNode(t2.val);
             help(null, t2.left, t.left);
             help(null, t2.right, t.right);
        }
        else if(t1==null&&t2==null){
            return;
        }
    }
    

    }


  • 0

    First, you should format your code.
    Then, you didn't connect left subtree and right subtree to root in the recursion.


  • 0
    X

    @jedihy Thanks for reply, but why the left subtree and right subtree are not connected to the root during recursion? Each step in the recursion, I changed the parameter to be t.left or t.right. I guess the problem might be the return type. It should nut be void here.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.