博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - 617. Merge Two Binary Trees
阅读量:7028 次
发布时间:2019-06-28

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

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input: 	Tree 1                     Tree 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  Output: Merged tree:	     3	    / \	   4   5	  / \   \ 	 5   4   7

 

Note: The merging process must start from the root nodes of both trees.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */import java.util.Queue;import java.util.LinkedList;public class Solution {    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {                if (t1 == null)            return t2;        if (t2 == null)            return t1;                t1.val += t2.val;        t1.left = mergeTrees(t1.left, t2.left);        t1.right = mergeTrees(t1.right, t2.right);                return t1;    }    }

 

转载于:https://www.cnblogs.com/wxisme/p/7201377.html

你可能感兴趣的文章
Maven是什么
查看>>
ArrayList的输出以及一些问题
查看>>
相关分析sas
查看>>
web -- Angularjs 备忘录应用
查看>>
sklearn学习笔记
查看>>
SQL Server 数据分页查询
查看>>
python之路day06-python2/3小区别,小数据池的概念,编码的进阶str转为bytes类型,编码和解码...
查看>>
angularjs 指令(directive)详解(2)
查看>>
2015-2016 ACM-ICPC, NEERC, Southern Subregional Contest J Cleaner Robot
查看>>
leapMotion简介
查看>>
增量更新项目时的备份MyBak
查看>>
图灵成立七周年——经典回顾
查看>>
iOS常用的设计模式
查看>>
[十二省联考2019]春节十二响
查看>>
HL AsySocket 服务开发框架 - 总体思路与架构
查看>>
安全原理
查看>>
web前端中的一些注释表达法
查看>>
Kotlin学习与实践 (八)集合的函数式 lambda API
查看>>
Kotlin学习与实践 (三)fun 函数
查看>>
[原]Unity3D深入浅出 - 脚本开发基础(Scripts)
查看>>