merge two binary trees

Given two binary trees, imagine that when you overlay one of them on top of the other, some of the nodes of the two binary trees will overlap.

You need to merge them into a new binary tree. The merging rule is that if two nodes overlap, their values ​​are added as the new value after the node is merged, otherwise the node that is not NULL will be directly used as the node of the new binary tree.

输入: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
输出: 
合并后的树:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

There are many solutions to this problem: mainly recursion, iteration, DFS, BFS

The first thing that comes to mind is to use the pre-order, in-order, and post-order traversal processing of the tree

recursion

preorder traversal solution

class Solution(object):
    def mergeTrees(self, t1, t2):
        if t1 is None and t2 is None:
            return
        if t1 is None:
            return t2
        if t2 is None:
            return t1
        t = TreeNode(t1.val + t2.val)
        t.left = self.mergeTrees(t1.left, t2.left)
        t.right = self.mergeTrees(t1.right, t2.right)
        return t

Inorder traversal solution

class Solution(object):
    def mergeTrees(self, t1, t2):
        if t1 is None and t2 is None:
            return
        if t1 is None:
            return t2
        if t2 is None:
            return t1
        t_left = self.mergeTrees(t1.left, t2.left)
        t = TreeNode(t1.val + t2.val)
        t.left = t_left
        t.right = self.mergeTrees(t1.right, t2.right)
        return t

post-order traversal solution

class Solution(object):
    def mergeTrees(self, t1, t2):
        if t1 is None and t2 is None:
            return
        if t1 is None:
            return t2
        if t2 is None:
            return t1
        t_left = self.mergeTrees(t1.left, t2.left)
        t_right = self.mergeTrees(t1.right, t2.right)
        t = TreeNode(t1.val + t2.val)
        t.left = t_left
        t_right = t_right
        return t

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325059180&siteId=291194637