zoukankan      html  css  js  c++  java
  • [Leetcode] Binary tree -- 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.

    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.

    Solution:

    1. use recursive time complexity o(min(m,n)) m is vertex number of t1, n is the vertex number of t2

    #combine the node to left tree t1. If node are overlapped, then add valu to t1.val. else return t1 or t2 if they are null repsectively.

    1         if t1 is None:
    2             return t2
    3         if t2 is None:
    4             return t1
    5         t1.val += t2.val
    6         t1.left = mergeTrees(t1.left, t2.left)
    7         t1.right = mergeTrees(t1.right, t2.right)
    8         
    9         return t1

    2.   use iterative way

     1        if t1 is None:
     2             return t2
     3         st = []
     4         st.append((t1,t2))
     5         while (len(st)):
     6             nodes = st.pop()
     7             r1 = nodes[0]
     8             r2 = nodes[1]
     9             if r1 is None or r2 is None:
    10                 continue
    11             r1.val += r2.val
    12             st.append((r1.left, r2.left))
    13             st.append((r1.right, r2.right))
    14                 
    15             if r1.left is None and r2.left is not None:
    16                 r1.left = r2.left
    17             if r1.right is None and r2.right is not None:
    18                 r1.right = r2.right
    19 
    20         return t1
  • 相关阅读:
    BZOJ BLO 1123 (割点)【双连通】
    P4291 [HAOI2008]排名系统
    P3165 [CQOI2014]排序机械臂
    P3224 [HNOI2012]永无乡
    P1169 [ZJOI2007]棋盘制作
    P2303 [SDOi2012]Longge的问题
    P2216 [HAOI2007]理想的正方形
    P2473 [SCOI2008]奖励关
    P2617 Dynamic Rankings
    P2518 [HAOI2010]计数
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7292077.html
Copyright © 2011-2022 走看看