当前位置:网站首页>leetcode 617 合并二叉树
leetcode 617 合并二叉树
2022-04-22 06:09:00 【Jack_joker】
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
使用深度优先搜索合并两个二叉树。从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。
两个二叉树的对应节点可能存在以下三种情况,对于每种情况使用不同的合并方式。
如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。
对一个节点进行合并之后,还要对该节点的左右子树分别进行合并。
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null){
return root2;
}
if(root2 == null){
return root1;
}
TreeNode mergeNode = new TreeNode(root1.val + root2.val);
mergeNode.left = mergeTrees(root1.left,root2.left);
mergeNode.right = mergeTrees(root2.right ,root1.right);
return mergeNode;
}
}
版权声明
本文为[Jack_joker]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Jack_joker/article/details/121394699
边栏推荐
- CAN总线中继网桥在新能源测试系统中的应用。
- 替代 FE1.1s HUB读卡主控芯片-MA8601
- Design of second-order RC low-pass filter for PWM wave to DC
- miniPCIe接口CAN卡为工控机扩展CAN通道
- QT qfile deletes the last n bytes of data in the file
- C技能树测评——0415体验日记
- C skill tree evaluation - 0415 experience diary
- [mcukeys] a general, flexible, configurable and portable implementation of key event processing
- HDMI2. Design circuit comparison between asw3642 and ts3dv642
- 数字ic设计有前途吗?职业发展,薪资待遇如何?
猜你喜欢

RT thread software package production and release process

Introduction to basic terms of machine learning

PL2586设计电路|PL2586替代FE1.1S电路图|USB2.0HUB工业级集线器方案设计

Sss1700 qfn36 single chip designs a USB typec headset | supports the automatic switching of USB headset scheme between wire control and European and American regulations

Fire fighting equipment optical fiber networking can to optical fiber converter

Analysis of running process of stm32wb55 Bluetooth protocol stack

STM32 learning record 0005 - JLINK download and debugging

STM32学习记录——开发环境安装

STM32学习记录0004——ISP串口下载

CS5202芯片规格书|CS5202替代CS5212|HDMI转VGA芯片
随机推荐
Is there any difference in the worst impedance processing you have encountered?
RT thread sensor software package classification
HDMI switcher scheme | 3 in and 1 out HDMI switcher | 5 in and 1 out hdmi2 Design circuit of ag7111 0 switcher
SSS1700
rt-thread 移植BSP驱动 uart篇
STM32学习记录0001——学习准备
Ag9310mcq supports the design reference circuit of mother seat forward and reverse plug typec to HDMI projection scheme
集成电路模拟版图入门-版图基础学习笔记(二)
Can transparent recording cloud gateway enables construction machinery
阿里云部署RSSHub踩坑笔记
Dcoker installation
First order digital low-pass filter - C language / Matlab implementation
微信小程序 canvas 画简单的仪表盘 渐近色
GridView of QML realizes sliding grid layout
CS5213新版规格书|CS5213新版说明书|HDMI转VGA带音频信号输出方案设计
CS5268开发TypeC转HDMI+VGA+PD+U3+3.5音频五合一扩展音视频转换方案参考设计
MA8608奇岩USB 2.0高速4端口USB HUB集线器控制器芯片方案
利用线程工厂设定线程池中线程名称
STM32 timer generates event Tim_ GenerateEvent
CAN光纤光端机在光电滑环中的应用