1. 程式人生 > >JavaScript刷LeetCode -- 617. Merge Two Binary Trees

JavaScript刷LeetCode -- 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.

二、題目大意

  將兩顆二叉樹合併,如果節點重合,則新的節點取兩個節點的和值。

三、解題思路

   遞迴。

四、程式碼實現

var mergeTrees = (t1, t2) => {
  if (!t1) {
    return t2
  }
  if (!t2) {
    return t1
  }
  const root = new TreeNode(t1.val + t2.val)
  root.left = mergeTrees(t1.left, t2.left)
  root.right = mergeTrees(t1.right, t2.right)

  return root
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。