LeetCode - 617. Merge Two Binary Trees

617. Merge Two Binary Trees

Recursion

1. update current value
2. recurse left and right

not in-place

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if not t1 and not t2: return None
        if not t1:
            left = self.mergeTrees(None, t2.left)
            right = self.mergeTrees(None, t2.right)
            value = t2.val
        elif not t2:
            left = self.mergeTrees(t1.left, None)
            right = self.mergeTrees(t1.right, None)
            value = t1.val
        else:
            left = self.mergeTrees(t1.left, t2.left)
            right = self.mergeTrees(t1.right, t2.right)
            value = t1.val + t2.val
        root = TreeNode(value)
        root.left = left
        root.right = right
        return root

some in-place, some not:

class Solution:
    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
        if None in (t1, t2): return t1 or t2
        cur = ListNode(t1.val+t2.val)
        cur.left = self.mergeTrees(t1.left, t2.left)
        cur.right = self.mergeTrees(t1.right, t2.right)
        return cur

in-place: write to t1

class Solution:
    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
        if None in (t1, t2): return t1 or t2
        t1.val += t2.val
        t1.left = self.mergeTrees(t1.left, t2.left)
        t1.right = self.mergeTrees(t1.right, t2.right)
        return t1

Iterative

in-place

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if not t1: return t2
        q = collections.deque([t1, t2])
        while q:
            n1 = q.popleft()
            n2 = q.popleft()
            if not n2: continue
            n1.val += n2.val
            if not n1.left:
                n1.left = n2.left
            else:
                q.append(n1.left)
                q.append(n2.left)
            if not n1.right:
                n1.right = n2.right
            else:
                q.append(n1.right)
                q.append(n2.right)
        return t1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值