【LeetCode每日一题】[简单]617. 合并二叉树
617. 合并二叉树
题目来源link
算法思想:树,递归,深度优先遍历
题目:
java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 != null){
return t2;
}//[],[1]这样的情形;
dfs(t1, t2);//深度递归,将结果保存在t1中
return t1;
}
public void dfs(TreeNode t1, TreeNode t2){
if(t1 == null || t2 == null){
return;
}//任意有一个节点null,则返回
dfs(t1.left, t2.left);//左子树递归
dfs(t1.right, t2.right);//右子树递归
//递归完成后,此时有三种情况:
//1.t1,t2节点均不为空,则val加起来
if(t1 != null && t2 != null){
t1.val = t1.val + t2.val;
}
//2.t1左节点为空,t2左节点不为空,则t1左节点指向t2左节点
if(t1.left == null && t2.left != null){
t1.left = t2.left;
}
//3.t1右节点为空,t2右节点不为空,则t1右节点指向t2右节点
if(t1.right == null && t2.right != null){
t1.right = t2.right;
}
//其他情况:如,t2的左右节点为空,因为结果保存在t1,所以不需要任何操作
}
}
leetcode官方解答–java代码
链接: link.
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}//t1,t2任意为空,则返回另一个;
TreeNode merged = new TreeNode(t1.val + t2.val);//新建节点
merged.left = mergeTrees(t1.left, t2.left);//左子树递归
merged.right = mergeTrees(t1.right, t2.right);//右子树递归
return merged;
}
}