数据结构与算法:合并二叉树

153 篇文章 0 订阅
88 篇文章 0 订阅

描述
已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。

合并二叉树

public class MergeTwoTrees {

     static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
     }

    /**
     *
     * @param t1 TreeNode类
     * @param t2 TreeNode类
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        //总体思想(递归):以t1为根本,将t2拼接到t1中,具体分一下几种情况:
        //(1)t1不为空,t2为空
        //(2)t1为空,t2不为空
        //(3)t1与t2都不为空

        if (t1 == null && t2 == null)
            return null;

        //(1)t1不为空,t2为空
        if(t1!=null && t2 == null){
            return t1;
        }
        //(2)t1为空,t2不为空
        if(t1==null && t2!=null){
            return t2;
        }
        //(3)t1与t2都不为空
        if(t1 != null && t2 != null){
            t1.val += t2.val;//合并数据
            t1.left = mergeTrees(t1.left,t2.left);//递归左子树
            t1.right = mergeTrees(t1.right,t2.right);//递归右子树
        }
        return t1;
    }

    public static void main(String[] args) {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值