领扣LintCode算法问题答案-1126. 合并两棵二叉树
发布日期:2021-06-30 17:09:57 浏览次数:3 分类:技术文章

本文共 1935 字,大约阅读时间需要 6 分钟。

领扣LintCode算法问题答案-1126. 合并两棵二叉树

目录

1126. 合并两棵二叉树

描述

给出两棵二叉树,当你用其中一棵覆盖另一棵时,两棵树的一些节点会发生重叠,而其他节点则不会重叠。

您需要将它们合并到一棵新的二叉树中。 合并的规则是如果两个节点重叠,则将节点值加起来作为合并节点的新值。 否则,非空的节点将用作新树的节点。

合并过程必须从两个树的根节点开始。

样例 1:

输入: {1,3,2,5}{2,1,3,#,4,#,7}输出:{3,4,5,5,4,#,7}解释:	树 1                     树 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  			合并的树:	     3	    / \	   4   5	  / \   \ 	 5   4   7

样例 2:

输入: {1}{1,2}输出:{2,2}

题解

/** * 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; } int v1 = t1 == null ? 0 : t1.val; int v2 = t2 == null ? 0 : t2.val; TreeNode root = new TreeNode(v1 + v2); if (t1 == null) {
root.left = t2.left; root.right = t2.right; } else if (t2 == null) {
root.left = t1.left; root.right = t1.right; } else {
root.left = mergeTrees(t1.left == null ? null : t1.left, t2.left == null ? null : t2.left); root.right = mergeTrees(t1.right == null ? null : t1.right, t2.right == null ? null : t2.right); } return root; }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108841722 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1133. 团购
下一篇:领扣LintCode算法问题答案-1119. 三个数的最大乘积

发表评论

最新留言

很好
[***.229.124.182]2024年05月02日 01时53分41秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章