LeetCode题解:合并二叉树
2022-05-19 本文已影响0人
搬码人
题目描述
已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。例如:
示例
输入:{1,3,2,5},{2,1,3,#,4,#,7}
输出:{3,4,5,5,4,#,7}
方法
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
// write code here
if(t1==null){
return t2;
}
if(t2==null){
return t1;
}
TreeNode tree = new TreeNode(t1.val+t2.val);
tree.left = mergeTrees(t1.left,t2.left);
tree.right = mergeTrees(t1.right,t2.right);
return tree;
}
}