[swift] LeetCode 617. Merge Two Binary Trees

栏目: Swift · 发布时间: 6年前

内容简介: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 n

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.

func mergeTrees(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {
    let root = mergeNote(t1, t2)
    root?.left = mergeTrees(t1?.left, t2?.left)
    root?.right = mergeTrees(t1?.right, t2?.right)
 
    return root
}
 
func mergeNote(_ t1: TreeNode?, _ t2: TreeNode?) -> TreeNode? {
    if let c1 = t1, let c2 = t2 {
        return TreeNode(c1.val + c2.val)
    } else if let c1 = t1 {
        return TreeNode(c1.val)
    } else if let c2 = t2 {
        return TreeNode(c2.val)
    } else {
        return nil
    }
}
[swift] LeetCode 617. Merge Two Binary Trees [swift] LeetCode 617. Merge Two Binary Trees

(随着网站访问量的激增,服务器配置只得一再升级以维持网站不“404 Not Found”,所以网站的维护费用也在不断上涨……(目前的阿里云服务器ECS+云数据库RDS+域名购买+七牛云的费用是2200元/年),为了能不放弃该网站,所以我又把打赏链接放上来啦~所有打赏金额都会被记账并投入博客维护中,感谢厚爱,多多关照~)


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Java 8函数式编程

Java 8函数式编程

[英] Richard Warburton / 王群锋 / 人民邮电出版社 / 2015-3 / 39.00元

通过每一章的练习快速掌握Java 8中的Lambda表达式 分析流、高级集合和其他Java 8类库的改进 利用多核CPU提高数据并发的性能 将现有代码库和库代码Lambda化 学习Lambda表达式单元测试和调试的实践解决方案 用Lambda表达式实现面向对象编程的SOLID原则 编写能有效执行消息传送和非阻塞I/O的并发应用一起来看看 《Java 8函数式编程》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具