美文网首页
617. Merge Two Binary Trees

617. Merge Two Binary Trees

作者: 荔枝不吃 | 来源:发表于2017-06-22 11:48 被阅读0次

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)

相关文章

网友评论

      本文标题:617. Merge Two Binary Trees

      本文链接:https://www.haomeiwen.com/subject/cmtfcxtx.html