A daily problem --- LeetCode (617) merge binary tree

Subject description:

Given two binary tree, when you imagine them to one another on the cover, some nodes will overlap two binary tree.
You will need to merge them into a new binary tree. Consolidation of the rule is that if two nodes overlap, their values are added as a new value after the merger node,
or the node is not NULL will direct the new node as a binary tree.

 

Thinking:
AB synchronous recursive tree with two A and B return to update A
recursive process:
if the current node is empty A return current node B
if the current node B returns the current node A is empty
(this case is already included in both) AB are two current node is empty or null
is not empty then to return to the val a is added to B val current node
returns t1 root

class Solution(object):
    def mergeTrees(self, t1, t2):
        
        if not t1:
            return t2
        if not t2:
            return t1
        t1.val+=t2.val
        t1.left = self.mergeTrees(t1.left,t2.left)
        t1.right = self.mergeTrees(t1.right,t2.right)
        return t1

Link: https: //leetcode-cn.com/problems/merge-two-binary-trees/solution/zhi-xing-yong-shi-1ms-ji-bai-100-by-zmillionaire/

 

Guess you like

Origin www.cnblogs.com/fighting25/p/11487344.html