Leetcode题解-617. Merge Two Binary Trees

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.

思路

这根遍历一棵二叉树的思路是一样的,这里用先序遍历的方法。需要注意的小细节就是t1、t2是否为空以及传给左右子树的t1、t2分别该是什么

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {      
        if(t1 == NULL && t2 == NULL) return NULL;
        TreeNode* result = new TreeNode(((t1 == NULL) ? 0 : t1->val) + ((t2 == NULL) ? 0 : t2->val));
        result->left = mergeTrees(((t1 == NULL) ? NULL : t1->left) , ((t2 == NULL) ? NULL : t2->left));
        result->right =  mergeTrees(((t1 == NULL) ? NULL : t1->right) , ((t2 == NULL) ? NULL : t2->right));
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要用Python时滞微分方程的数值,可以使用scipy.integrate库中的delayed函数。具体步骤如下: 1. 导入必要的库: ```python import numpy as np from scipy.integrate import solve_delayed ``` 2. 定义时滞微分方程: ```python def f(t, y, yd): tau = 1.0 dydt = -y + yd(t - tau) return dydt ``` 其中,t表示时间,y表示未知函数,yd表示时滞函数,tau表示时间延迟。 3. 定义初始条件和时间网格: ```python y0 = [1.0] tmax = 10.0 dt = 0.01 tgrid = np.arange(0, tmax+dt, dt) ``` 其中,y0表示y在t=0时的值,tmax表示模拟的最长时间,dt表示时间步长,tgrid表示时间网格。 4. 定义时滞函数: ```python def yd(u): return np.interp(u, tgrid, yhist) ``` 其中,u表示时滞时间,yhist表示y在之前时间的值。 5. 方程: ```python sol = solve_delayed(f, y0, tgrid, yd) ``` 其中,sol是一个对象,包含了数值和其他信息。 6. 提取数值: ```python y = sol.y[0] ``` 其中,sol.y是一个数组,包含了数值。 完整代码如下: ```python import numpy as np from scipy.integrate import solve_delayed def f(t, y, yd): tau = 1.0 dydt = -y + yd(t - tau) return dydt y0 = [1.0] tmax = 10.0 dt = 0.01 tgrid = np.arange(0, tmax+dt, dt) def yd(u): return np.interp(u, tgrid, yhist) yhist = np.zeros_like(tgrid) yhist[0] = y0[0] for i in range(1, len(tgrid)): yhist[i] = yhist[i-1] + dt * (-yhist[i-1]) sol = solve_delayed(f, y0, tgrid, yd) y = sol.y[0] import matplotlib.pyplot as plt plt.plot(tgrid, y, label='y') plt.legend() plt.show() ``` 这个例子中,时滞函数是y在之前时间的值,因此我们先用欧拉出y在所有时间点的值,然后用np.interp函数将其转换为时滞函数。最后,我们时滞微分方程并绘制数值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值