[Algorithm] 617. Merge Two Binary Trees

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

 

复制代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} t1
 * @param {TreeNode} t2
 * @return {TreeNode}
 */
var mergeTrees = function(t1, t2) {
    
    if (!t1 && !t2) {
        return null;
    }
    
    return helper(t1, t2);
};

function helper (t1, t2) {
    if (!t1) {
        return t2;
    }
    
    if (!t2) {
        return t1;
    }
    
    let sum = (t1.val || 0) + (t2.val || 0);
    let newNode = new TreeNode(sum);
    newNode.left = helper(t1.left, t2.left);
    newNode.right = helper(t1.right, t2.right);
    return newNode;
}
复制代码

 

posted @   Zhentiw  阅读(174)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-12-22 [Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript
2017-12-22 [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
2017-12-22 [Recompose] Stream Props to React Children with RxJS
2017-12-22 [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component
2017-12-22 [Recompose] Handle React Events as Streams with RxJS and Recompose
2017-12-22 [Recompose] Stream a React Component from an Ajax Request with RxJS
2017-12-22 [Recompose] Pass a React Prop to a Stream in RxJS
点击右上角即可分享
微信分享提示