14 ms , beat 100%, speed up cases when t1 or t2 or any subtrees are null


  • 0
    E

    The idea is travel the tree using recursive.
    Stop the recursive when t1 or t2 or subtrees are null.

    public class Solution {
        public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
            TreeNode res = null;
            if(t1==null){
                return t2;
            }else if(t2==null){
                return t1;
            }
            t1.val += t2.val;
            merge(t1.left, t2.left, t1, 0);
            merge(t1.right, t2.right, t1, 1);
            return t1;
        }
        
        /* lr = 0 => left child
            lr = 1 +=> right child
        */
        
        private void merge(TreeNode t1, TreeNode t2, TreeNode parent, int lr){
            if(t1!=null && t2!=null){
                t1.val += t2.val;
                merge(t1.left, t2.left, t1, 0);
                merge(t1.right, t2.right, t1, 1);
            }else if(t1==null && t2!=null){
                if(lr==0){
                    parent.left = t2;
                }else{
                    parent.right = t2;
                }
            }else if(t1!=null && t2==null){
                //do nothing
            }
        }
    }
    
    

Log in to reply
 

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