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

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

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.

题意:归并两个树,说简单点就是,都有的相加,没有的互补

遍历相加就行了,为了省空间,我们就用t1做基板就行了

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/Moriarty-cx/p/9781632.html

你可能感兴趣的文章
WEB安全之解决CC攻击
查看>>
Html5 01(data-attributes、form-types【只在移动端使用】、svg)
查看>>
python之random模块
查看>>
visor 发布
查看>>
nginx 隐藏版本信息
查看>>
百事世界杯之旅
查看>>
Launch VINS-Mono with Realsense D435i in RTAB-Map
查看>>
以一点为中心旋转动画实现,摇摆动画
查看>>
js去除范围内所有标签并显示指定字符串
查看>>
结对项目进度2
查看>>
git + git flow 的简单介绍
查看>>
Servlet详解(四)--Request与Response
查看>>
如果我们想要交换两个数字,就可以使用位运算
查看>>
求给出第 K个 N位二进制数,该二进制数不得有相邻的“1”
查看>>
P1059 明明的随机数【去重排序】
查看>>
HDU 1060 Leftmost Digit【log10/求N^N的最高位数字是多少】
查看>>
tomcat配置文件web.xml与server.xml解析--重要
查看>>
【C语言】《C Primer Plus》递归:以二进制形式输出整数
查看>>
Ubuntu-proxy代理配置
查看>>
WordCountPro
查看>>