Golang simple recursive solution


  • 0

    Just simply traversing from root to lear, while merging nodes into t1.

    func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
    	if t1 == nil && t2 == nil {
    		return nil
    	} else if t1 == nil {
    		return t2
    	} else if t2 == nil {
    		return t1
    	}
    
    	t1.Val = t1.Val + t2.Val
    	r := t1
    	helper(t1, t2)
    	return r
    }
    
    func helper(p1, p2 *TreeNode) {
    	switch { // handle left
    	case p1.Left == nil && p2.Left != nil:
    		p1.Left = p2.Left
    	case p1.Left != nil && p2.Left != nil:
    		p1.Left.Val = p1.Left.Val + p2.Left.Val
    		helper(p1.Left, p2.Left)
    	}
    
    	switch { // handle right
    	case p1.Right == nil && p2.Right != nil:
    		p1.Right = p2.Right
    	case p1.Right != nil && p2.Right != nil:
    		p1.Right.Val = p1.Right.Val + p2.Right.Val
    		helper(p1.Right, p2.Right)
    	}
    }
    

Log in to reply
 

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