617. Merge Two Binary Trees

问题描述

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

思路

recursive
把第二棵树的值,直接加到第一棵树上,或者重新创建一棵树

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: return t2
        if not t2: return t1
        t1.val += t2.val
        t1.left = self.mergeTrees(t1.left, t2.left)
        t1.right = self.mergeTrees(t1.right, t2.right)
        return t1
class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if not t1 and not t2: return None
        ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
        ans.left = self.mergeTrees(t1.left, t2.left)
        ans.right = self.mergeTrees(t1.right, t2.right)
        return ans
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,199评论 0 10
  • 21年前,选择了教师作为职业,从踌躇满志的春华,走到了如今黄叶满地的萧秋。没取得过什么拿得出手的值得炫耀的成绩,却...
    艾艾琴阅读 2,563评论 0 4
  • “多得是,你理解却未曾经历的事。” 前几天,萍子阿姨找我聊天,倾诉了一件事,我不相信真的有这么悲惨的经历会降临在一...
    Lee三猪阅读 2,732评论 0 1
  • 你会做计划吗? 有时真的很想努力多做点事,或者把之前落下的事都补上。就会在把这一天排的满满的,想一口吃成大胖子。结...
    豆浆油条_bdb7阅读 1,247评论 0 0
  • 刚通过中关村地铁的安检,就听到一个穿着黑棉袄的黑黝黝的女生对我喊: 哎,美女,请问我可以微信… 我瞥了她一眼,没等...
    Lunar晴阅读 3,025评论 0 4

友情链接更多精彩内容