上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
}
};
java 解法, 执行用时: 0 ms, 内存消耗: 42.6 MB, 提交时间: 2023-08-14 09:23:50
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if ( root1 == null ) return root2;
if ( root2 == null ) return root1;
TreeNode root3 = new TreeNode(root1.val + root2.val);
root3.left = mergeTrees(root1.left, root2.left);
root3.right = mergeTrees(root1.right, root2.right);
return root3;
}
}
golang 解法, 执行用时: 20 ms, 内存消耗: 6.8 MB, 提交时间: 2021-07-19 09:24:55
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
if t1 == nil {
return t2
}
if t2 == nil {
return t1
}
var t3 = &TreeNode{}
t3.Val = t1.Val + t2.Val
t3.Left = mergeTrees(t1.Left, t2.Left)
t3.Right = mergeTrees(t1.Right, t2.Right)
return t3
}
python3 解法, 执行用时: 160 ms, 内存消耗: N/A, 提交时间: 2018-08-24 20:46:16
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 == None:
return t2
if t2 == None:
return t1
t3 = TreeNode(t1.val + t2.val)
t3.left = self.mergeTrees(t1.left, t2.left)
t3.right = self.mergeTrees(t1.right, t2.right)
return t3
javascript 解法, 执行用时: 120 ms, 内存消耗: N/A, 提交时间: 2018-08-24 20:44:14
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} t1
* @param {TreeNode} t2
* @return {TreeNode}
*/
var mergeTrees = function(t1, t2) {
if ( t1 == null )
return t2
if ( t2 == null )
return t1
var t3 = new TreeNode(t1.val + t2.val);
t3.left = mergeTrees(t1.left, t2.left);
t3.right = mergeTrees(t1.right, t2.right);
return t3;
};