[swift] LeetCode 617. Merge Two Binary Trees

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

内容简介: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元/年),为了能不放弃该网站,所以我又把打赏链接放上来啦~所有打赏金额都会被记账并投入博客维护中,感谢厚爱,多多关照~)


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

查看所有标签

猜你喜欢:

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

算法谜题

算法谜题

Anany Levitin、Maria Levitin / 赵勇、徐章宁、高博 / 人民邮电出版社 / 2014-1-1

算法是计算机科学领域最重要的基石之一。算法谜题,就是能够直接或间接地采用算法来加以解决的谜题。求解算法谜题是培养和锻炼算法思维能力一种最有效和最有乐趣的途径。 本书是一本经典算法谜题的合集。本书包括了一些古已有之的谜题,数学和计算机科学有一部分知识就发源于此。本书中还有一些较新的谜题,其中有一部分谜题被用作知名IT企业的面试题。全书可分为4个部分,分别是概览、谜题、提示和答案。概览介绍了算法......一起来看看 《算法谜题》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具