Short Java Solution - self explanatory


  • 0
    A
    public class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            // algorithm 2017/06/11: recursive solution. Merging left child and right child separately.
            if (null == t1) {
                return t2;
            }
            if (null == t2) {
                return t1;
            }
            // both are not null
            TreeNode mergedRoot = new TreeNode(t1.val + t2.val);
            mergedRoot.left     = mergeTrees(t1.left, t2.left);
            mergedRoot.right    = mergeTrees(t1.right, t2.right);
    
            return mergedRoot;
        }
    }

Log in to reply
 

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