LeetCode #617 Merge Two Binary Trees

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode #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.

题意:以数组的方式给出两棵二叉树,将两棵树以根为底将两棵树合并起来,当且仅当两棵树同个位置的节点都有值时进行相加作为新节点值,不然就将其中一棵不为空的节点值作为新节点。

解法:通过中序遍历两棵树,依次返回不为空的新节点更新第一棵树节点,当遍历过程中发现两棵树中其中一棵为空时直接将另外一棵接上即可,若两棵都不为空则按照规则更新第一棵树节点,并递归中序遍历继续更新两棵树。

参考代码:

 1 class Solution:
 2     def mergeTrees(self, t1, t2):
 3         """
 4         :type t1: TreeNode
 5         :type t2: TreeNode
 6         :rtype: TreeNode
 7         """
 8         if t1 and t2:
 9             t1.val = t1.val+t2.val
10             t1.left = self.mergeTrees(t1.left, t2.left)
11             t1.right = self.mergeTrees(t1.right, t2.right)
12             return t1
13         elif t1:
14             return t1
15         elif t2:
16             return t2

 

以上是关于LeetCode #617 Merge Two Binary Trees的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 617. Merge Two Binary Trees

LeetCode(617) Merge Two Binary Trees

Leetcode_easy617. Merge Two Binary Trees

leetcode No617. Merge Two Binary Trees

leetcode No617. Merge Two Binary Trees

[LeetCode&Python] Problem 617. Merge Two Binary Trees