Java Recursive Solution | Beats 100% of Java Solutions till now


  • 0
    M
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            if (t1 == null && t2 != null) {
                return t2;
            } else if (t1 != null && t2 == null) {
                return t1;
            } 
            
            return mergeTreesUtil(t1, t2);
            
        }
        
        private TreeNode mergeTreesUtil(TreeNode t1, TreeNode t2) {
            if (t1 == null || t2 == null) {
                return null;
            }
            
            if (t1 != null && t2 != null) {
                t1.val += t2.val;
            }
            
            if (mergeTreesUtil(t1.left, t2.left) == null) {
                if (t1.left == null) t1.left = t2.left;
            }
            
            if (mergeTreesUtil(t1.right, t2.right) == null) {
                if (t1.right == null) t1.right = t2.right;
            }
            
            return t1;
        }
    

Log in to reply
 

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