版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/83573289
给出两个二叉树,并想象当你把其中一个覆盖另一个时,两棵树的一些节点重叠,而其他节点则不重叠。
您需要将它们合并到一个新的二叉树中。 合并规则是,如果两个节点重叠,则将节点值加起来作为合并节点的新值。 否则,非空节点将用作新树的节点。
样例
输入:
树 1 树 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并的树:
3
/ \
4 5
/ \ \
5 4 7
注意事项
合并过程必须从两个树的根节点开始。
解题思路:
前序遍历,依次相加即可。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param t1: the root of the first tree
* @param t2: the root of the second tree
* @return: the new binary tree after merge
*/
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// Write your code here
if(t1==null && t2==null)
return null;
else if(t1 == null)
return t2;
else if(t2 == null)
return t1;
//两者都不为空,则叠加
t1.val += t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}