【LeetCode每日一题】[简单]617. 合并二叉树

【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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值