合并两棵二叉树(7 lines)

本文介绍了一种合并两棵二叉树的方法,当两棵树有重叠节点时,将节点值相加作为新节点值;当没有重叠时,保留非空节点。通过递归方式实现合并过程。

合并两棵二叉树

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. 遇到树问题,首先想到递归
  2. 将t2的val加到t1,返回当前处理的t1结点
  3. 如果t1为null,把引用指向t2
  4. 需要注意处理null的问题

代码

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

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

本题以及其它leetcode题目代码github地址: github地址

   C. Cyclic Merging time limit per test2 seconds memory limit per test256 megabytes    You are given n non-negative integers a1,a2,…,an arranged on a ring. For each 1≤i<n , ai and ai+1 are adjacent; a1 and an are adjacent. You need to perform the following operation exactly n−1 times: Choose any pair of adjacent elements on the ring, let their values be x and y , and merge them into a single element of value max(x,y) with cost max(x,y) . Note that this operation will decrease the size of the ring by 1 and update the adjacent relationships accordingly. Please calculate the minimum total cost to merge the ring into one element. DeepL 翻译    给你 n 个非负整数 a1,a2,…,an 在一个环上排列。每个 1≤i<n 中, ai 和 ai+1 相邻; a1 和 an 相邻。 您需要执行以下操作 ** 精确地** n−1 次: 在环上任意选择一对相邻元素,假设它们的值分别为 x 和 y ,然后将它们合并为一个值为 max(x,y) 的元素,合并代价为 max(x,y) 。 请注意,此操作将使环的大小减少 1 ,并相应地更新相邻关系。 请计算将环合并为一个元素的最小总成本。    Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104 ). The description of the test cases follows. The first line of each test case contains an integer n (2≤n≤2⋅105 ). The following line contains n integers a1,a2,…,an (0≤ai≤109 ). It is guaranteed that the sum of n over all test cases does not exceed 2⋅105 . DeepL 翻译    输入 每个测试包含多个测试用例。第一行包含测试用例的数量 t ( 1≤t≤104 )。测试用例说明如下。 每个测试用例的第一行都包含一个整数 n ( 2≤n≤2⋅105 )。 下一行包含 n 个整数 a1,a2,…,an ( 0≤ai≤109 )。 保证所有测试用例中 n 的总和不超过 2⋅105 。    Output For each test case, please print a single integer — the minimum total cost. DeepL 翻译    输出 请为每个测试用例打印一个整数 - 最小总成本。 Example InputCopy 3 4 1 1 3 2 2 0 2 7 1 1 4 5 1 4 1 OutputCopy 6 2 19    Note In the first test case, we can achieve a cost of 6 on [1,1,3,2] as follows: Merge indexes 1 and 2 with a cost of 1 , the ring becomes [1,3,2] . Merge indexes 1 and 3 with a cost of 2 , the ring becomes [3,2] . Merge indexes 1 and 2 with a cost of 3 , the ring becomes [3] . The total cost is 1+2+3=6 . It can be proven that it is impossible to achieve a lower cost; thus, the answer is indeed 6 . In the second test case, the only option is to merge the two elements, with a cost of 2 . DeepL 翻译    注 在第一个测试案例中,我们可以在 [1,1,3,2] 上实现 6 的成本,具体如下: 合并索引 1 和 2 的代价为 1 ,环变为 [1,3,2] 。 合并索引 1 和 3 ,代价为 2 ,索引环变为 [3,2] 。 合并索引 1 和 2 ,费用为 3 ,索引环变为 [3] 。 总成本为 1+2+3=6 。可以证明不可能有更低的成本,因此答案确实是 6 。 在第二个测试案例中,唯一的选择是合并两个元素,成本为 2 。import sys def solve(): data = list(map(int, sys.stdin.buffer.read().split())) t = data[0] idx = 1 out_lines = [] for _ in range(t): n = data[idx]; idx += 1 a = data[idx:idx+n]; idx += n total = 0 max_edge = 0 for i in range(n): x = a[i] y = a[(i + 1) % n] w = x if x > y else y # max(x, y) total += w if w > max_edge: max_edge = w out_lines.append(str(total - max_edge)) sys.stdout.write("\n".join(out_lines)) if __name__ == "__main__": solve() 解释这个思路
最新发布
11-18
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值