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:

Example from LeetCode

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

Solution:

function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}
var mergeTrees = function(t1, t2) {
      if(null !== t1 || null !== t2) {
          var tmp = new TreeNode(0);
          if(null !== t1) tmp.val += t1.val;
          if(null !== t2) tmp.val += t2.val;
          tmp.left = mergeTrees((t1 !== null) ? t1.left : null, (t2 !== null) ? t2.left : null);
          tmp.right = mergeTrees((t1 !== null) ? t1.right : null, (t2 !== null) ? t2.right : null);
          return tmp;
      }
      else return null;
  };

JavaScript中的对象初始化:
var object = new SomeFunc(para)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 4.2.3 我怕…… 我常常用……方式攻击/防御 其实我投射了…… 4.2.4 我因为……而导致现在的结局 就是因...
    兮兮AX阅读 1,688评论 0 0
  • 乌云 压的很低, 湖面上满是 黑影漆漆。 路过那些风, 路过那些雨, 也路过 风雨中的你 有人在弹吉他 有人在下棋...
    克莱辛先生阅读 832评论 0 1

友情链接更多精彩内容