Java Recursion, clear codes, easy to understand.


  • 0
    D
    public class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) 
        {
            return helper(t1, t2, null);
        }
        
        private TreeNode helper(TreeNode t1, TreeNode t2, TreeNode p)
        {
            if (t1 == null && t2 == null) { return null; }
            
            if (t1 == null)
            {
                p = new TreeNode(t2.val);
                p.left = helper(null, t2.left, p.left);
                p.right = helper(null, t2.right, p.right);
            }
            else if (t2 == null)
            {
                p = new TreeNode(t1.val);
                p.left = helper(t1.left, null, p.left);
                p.right = helper(t1.right, null, p.right);
            }
            else
            {
                p = new TreeNode(t1.val + t2.val);
                p.left = helper(t1.left, t2.left, p.left);
                p.right = helper(t1.right, t2.right, p.right);
            }
            
            return p;
        }
    }
    

Log in to reply
 

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