首页 > 其他分享 >leetcode 617. Merge Two Binary Trees

leetcode 617. Merge Two Binary Trees

时间:2023-05-30 18:02:37浏览次数:39  
标签:Binary right TreeNode self t2 Two Trees t1 left

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:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

更简略的:

def mergeTrees(self, t1, t2):
    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 and t1.left, t2 and t2.left)
    ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
    return ans

用and代替if明显是代码更少!

官方解答有错,修改了原有的输入数据:

public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
            return t2;
        if (t2 == null)
            return t1;
        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }
}

如果不用递归而使用迭代,采用队列实现,层序遍历BFS思想,当遇到2颗树对应的节点之一不为null时就需入队,同时在建立新树时也一样将对应的结果节点入队:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        # solution 2
        if not t1 and not t2:
            return None
        q1, q2 = collections.deque([t1]), collections.deque([t2])
        root = TreeNode(0)
        q = collections.deque([root])
        while q1 and q2:
            node1, node2, node = q1.popleft(), q2.popleft(), q.popleft()
            node.val = (node1 and node1.val or 0) + (node2 and node2.val or 0)
            if (node1 and node1.left) or (node2 and node2.left):
                q1.append(node1 and node1.left)                
                q2.append(node2 and node2.left)
                node.left = TreeNode(0)
                q.append(node.left)
            if (node1 and node1.right) or (node2 and node2.right):
                q1.append(node1 and node1.right)
                q2.append(node2 and node2.right)
                node.right = TreeNode(0)
                q.append(node.right)
        return root

空间复杂度O(max(M,N)), M、N为两颗树的节点个数。

注,关于deque可以直接判断其是否为空:

>>> import collections
>>> q=collections.deque([])
>>> if q:
...   print "Y"
... 
>>> q=collections.deque([1])
>>> if q:
...   print "x"
... 
x

标签:Binary,right,TreeNode,self,t2,Two,Trees,t1,left
From: https://blog.51cto.com/u_11908275/6381165

相关文章

  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......
  • leetcode 671. Second Minimum Node In a Binary Tree
    Givenanon-emptyspecialbinarytreeconsistingofnodeswiththenon-negativevalue,whereeachnodeinthistreehasexactlytwoorzerosub-node.Ifthenodehastwosub-nodes,thenthisnode'svalueisthesmallervalueamongitstwosub-nodes.G......
  • leetcode 107. Binary Tree Level Order Traversal II
    Givenabinarytree,returnthebottom-uplevelordertraversalofitsnodes'values.(ie,fromlefttoright,levelbylevelfromleaftoroot).Forexample:Givenbinarytree[3,9,20,null,null,15,7],3/\920/\157returnits......
  • leetcode 350. Intersection of Two Arrays II
    Giventwoarrays,writeafunctiontocomputetheirintersection.Example:Givennums1=[1,2,2,1],nums2=[2,2],return[2,2].Note:Eachelementintheresultshouldappearasmanytimesasitshowsinbotharrays.Theresultcanbeinanyorder.Foll......
  • leetcode 231. Power of Two
    Givenaninteger,writeafunctiontodetermineifitisapoweroftwo.classSolution(object):defisPowerOfTwo(self,n):""":typen:int:rtype:bool"""#-4???ifn>......
  • CF1398E Two Types of Spells 题解 set
    题目链接:https://codeforces.com/problemset/problem/1398/E题目大意你有一个集合,初始为空。有两种类型的元素,一种是普通元素,一种是强化元素,两种元素都有一个数值。有\(n\)次操作,每次操作会往集合中加入一个元素或者删除一个元素。每次操作后,你都需要确定集合中元素的一个......
  • Wallys/Qualcomm network chip/ipq9574/ipq9554/wireless connectivity solutions.
     QualcommWi-Fi7networkchipsolutionsIPQ9574andIPQ9554areadvancedwirelessconnectivitysolutionsdevelopedbyQualcommTechnologies.ThesechipsaredesignedtosupporttheWi-Fi7(802.11be)standard,whichofferssignificantimprovementsinspe......
  • [CVPR23 Highlight] Side Adapter Network for Open-Vocabulary Semantic Segmentatio
    **摘要本文提出了一个用于开放词汇语义分割的新框架SAN,将语义分割任务建模为区域识别问题,提取maskproposals并使用CLIP对mask进行识别。SAN可以重新利用CLIP的特征,因此其本身可以非常轻量;同时网络可以端到端地进行训练,从而使SAN适应冻结的CLIP模型。本文方法需要很少的参数量,且......
  • 文献阅读-Inferring Networks of Diffusion and Influence
    Authors: ManuelGomez-Rodriguez, JureLeskovec, AndreasKrause AuthorsInfo&ClaimsACMTransactionsonKnowledgeDiscoveryfromDataVolume5Issue4ArticleNo.:21pp1–37https://doi.org/10.1145/2086737.2086741  Abstract......
  • can't not find Node.js binary ''path",make sure Node.js is installed and in your
    vscode中node执行debug报错报错信息如下 思路1:检查node是否安装成功win+R输入cmd  能够正常显示版本号,则证明没有问题,接着换个思路 思路2:根据提示打开图示的'launch.json'文件,在页面补充 runtimeExecutable具体补充什么内容呢?在overflow中找到了nginx中需要补......