Java Solution


  • 0
    M

    Traversal using Pre Order.

    public class Solution {
        
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            return merge(t1, t2);
        }
        
        public TreeNode merge(TreeNode t1, TreeNode t2) {
            if (t1 == null && t2 == null) return null;
            
            TreeNode node = null;
            if (t1 != null && t2 != null) {
                node = new TreeNode(t1.val + t2.val);       
            } else if (t1 == null) {
                node = new TreeNode(t2.val);       
            } else {
                node = new TreeNode(t1.val);       
            }
            
            node.left = merge(t1 != null ? t1.left : null, t2 != null ? t2.left : null);
            node.right = merge(t1 != null ? t1.right : null, t2 != null ? t2.right : null);
            
            return node;
        }
    }
    

Log in to reply
 

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