-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path617.合并二叉树.js
82 lines (78 loc) · 1.88 KB
/
617.合并二叉树.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* @lc app=leetcode.cn id=617 lang=javascript
*
* [617] 合并二叉树
*
* https://leetcode.cn/problems/merge-two-binary-trees/description/
*
* algorithms
* Easy (78.92%)
* Likes: 987
* Dislikes: 0
* Total Accepted: 288.3K
* Total Submissions: 365.2K
* Testcase Example: '[1,3,2,5]\n[2,1,3,null,4,null,7]'
*
* 给你两棵二叉树: root1 和 root2 。
*
*
* 想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为
* null 的节点将直接作为新二叉树的节点。
*
* 返回合并后的二叉树。
*
* 注意: 合并过程必须从两个树的根节点开始。
*
*
*
* 示例 1:
*
*
* 输入:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
* 输出:[3,4,5,5,4,null,7]
*
*
* 示例 2:
*
*
* 输入:root1 = [1], root2 = [1,2]
* 输出:[2,2]
*
*
*
*
* 提示:
*
*
* 两棵树中的节点数目在范围 [0, 2000] 内
* -10^4 <= Node.val <= 10^4
*
*
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {TreeNode}
*/
var mergeTrees = function (root1, root2) {
// 一个树为空,则返回另一个
if (root1 === null) return root2;
if (root2 === null) return root1;
// 合并根节点
root1.val += root2.val;
// 合并左子树
root1.left = mergeTrees(root1.left, root2.left);
// 合并右子树
root1.right = mergeTrees(root1.right, root2.right);
return root1;
};
// @lc code=end