• [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
  • 相关阅读:
    实现一个最简单的flask应用程序
    python常识
    Flex布局
    ES6的promise的学习
    通过正则获取url参数
    dom0级事件和dom2级事件
    sea.js总结
    跨域的几种方式
    人生苦短,生命也就一次,机会也就一次
    新开的博客先和大家打个招呼吧!
  • 原文地址:https://www.cnblogs.com/anxin6699/p/7292077.html
Copyright © 2020-2023  润新知