文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
注意: 合并必须从两个树的根节点开始。
java实现方法1:
/**
* 合并两颗二叉树
*
* @param t1 二叉树t1
* @param t2 二叉树t2
* @return 合并后二叉树
*/
public TreeNode mergeTrees1(TreeNode t1, TreeNode t2) {
if (t1 == null)
return t2;
if (t2 == null)
return t1;
t1.val += t2.val;
t1.left = mergeTrees1(t1.left, t2.left);
t1.right = mergeTrees1(t1.right, t2.right);
return t1;
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方式1:
def merge_trees(t1: TreeNode, t2: TreeNode) -> TreeNode:
'''
合并两棵二叉树
Args:
t1: 二叉树t1
t2: 二叉树t2
Returns:
合并后的二叉树
'''
if t1 == None:
return t2
if t2 == None:
return t1
t1.val += t2.val
t1.left = merge_trees(t1.left, t2.left)
t1.right = merge_trees(t1.right, t2.right)
return t1
时间复杂度:O(n)
空间复杂度:O(n)
java实现方法2:
/**
* 合并二叉树
*
* @param t1 二叉树t1
* @param t2 二叉树t2
* @return 合并后二叉树
*/
public TreeNode mergeTrees2(TreeNode t1, TreeNode t2) {
if (t1 == null)
return t2;
Stack<TreeNode[]> stack = new Stack<>();
stack.push(new TreeNode[]{t1, t2});
while (!stack.isEmpty()) {
TreeNode[] t = stack.pop();
if (t[0] == null || t[1] == null) {
continue;
}
t[0].val += t[1].val;
if (t[0].left == null) {
t[0].left = t[1].left;
} else {
stack.push(new TreeNode[]{t[0].left, t[1].left});
}
if (t[0].right == null) {
t[0].right = t[1].right;
} else {
stack.push(new TreeNode[]{t[0].right, t[1].right});
}
}
return t1;
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方法2:
def merge_trees2(t1: TreeNode, t2: TreeNode) -> TreeNode:
'''
合并两棵二叉树
Args:
t1: 二叉树t1
t2: 二叉树t2
Returns:
合并后的二叉树
'''
if t1 == None:
return t2
if t2 == None:
return t1
stack = []
stack.append((t1, t2))
while stack:
t = stack.pop()
if t[0] == None or t[1] == None:
continue
t[0].val += t[1].val
if t[0].left == None:
t[0].left = t[1].left
else:
stack.append((t[0].left, t[1].left))
if t[0].right == None:
t[0].right = t[1].right
else:
stack.append((t[0].right, t[1].right))
return t1
时间复杂度:O(n)
空间复杂度:O(n)