合并两棵二叉树(7 lines)

来源:互联网 发布:腾讯已备案2级域名分发 编辑:程序博客网 时间:2024/06/03 23:48

合并两棵二叉树

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.

Example 1:

Input:     Tree 1                     Tree 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  Output: Merged tree:         3        / \       4   5      / \   \      5   4   7

Note: The merging process must start from the root nodes of both trees.

思路

  1. 遇到树问题,首先想到递归
  2. 将t2的val加到t1,返回当前处理的t1结点
  3. 如果t1为null,把引用指向t2
  4. 需要注意处理null的问题

代码

# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def mergeTrees(self, t1, t2):        """        :type t1: TreeNode        :type t2: TreeNode        :rtype: TreeNode        """        if t1 is not None and t2 is not None:            t1.val += t2.val            t1.left = self.mergeTrees(t1.left, t2.left)            t1.right = self.mergeTrees(t1.right, t2.right)        elif t1 is None and t2 is not None:            t1 = t2        return t1

本题以及其它leetcode题目代码github地址: github地址

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 校外怎么办北邮校园卡 报考身份证丢了怎么办 买房怎么办不取消低保 自考找不到真题怎么办 自考生考研没有档案怎么办 自考本科无学位怎么办 自考学位证书没拿到怎么办 自考毕业证出生日期错误怎么办 成考没有学位证怎么办 评职称学历认证怎么办 国家不承认学历怎么办 高考分数错了怎么办 签合同了不想干怎么办 贵港教育小学插班生怎么办 学校宿舍限瓦怎么办 苹果锁屏后wifi断开怎么办 兼职一天不给钱怎么办 五月孩子掉床怎么办 孩子五月份掉床怎么办 郑州怎么办暂住证凭条 郑州居住证凭条怎么办 宿舍虫子咬人怎么办 is语音注册频繁怎么办 苹果id注销了怎么办 网站突然打不开了怎么办 谷歌邮箱打不开怎么办 360借款无力承担怎么办 公司被收购期权怎么办 创业板连续亏损怎么办 国企合并后员工怎么办 资金密码忘记了怎么办? 大华电子秤称重不准怎么办 股票暂停上市散户怎么办 入股公司赔钱了怎么办 家里被虚报脱贫怎么办 技术入股想退股怎么办 想开店没有资金怎么办 想开店资金不够怎么办 要开店没资金怎么办 想开店缺少资金怎么办 刚刚开店没有资金怎么办