go solution


  • 0
    Y
    package tree
    
    func coalesce(p *Node) (res int) {
    	if p != nil {
    		res = p.Val
    	}
    	return
    }
    
    func r(p *Node) (res *Node) {
    	if p != nil {
    		res = p.R
    	}
    	return
    }
    
    func l(p *Node) (res *Node) {
    	if p != nil {
    		res = p.L
    	}
    	return
    }
    
    // O(log n) space and O(n) time solution
    func merge(p *Node, q *Node) *Node {
    	if p == nil && q == nil {
    		return nil
    	}
    	return &Node{
    		Val: coalesce(p, q),
    		L:   merge(l(p.L), l(q.L)),
    		R:   merge(r(p.R), r(q.R)),
    	}
    }
    

Log in to reply
 

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