617. Merge Two Binary Trees

Link: https://leetcode.com/problems/delete-columns-to-make-sorted/

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

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


題目翻譯:

給出兩個二叉樹並想像當你把其中一個覆蓋另一個時,兩棵樹的一些節點重疊,而其他樹則不重疊。

您需要將它們合併到一個新的二叉樹中。合併規則是,如果兩個節點重疊,則將節點值加起來作為合併節點的新值。否則,NOT null 節點將用作新樹的節點。

程式思路:

用 dfs 來實作此題目,不過為了不破壞原本的 t1,t2,所以我自己用了一個新的樹,如果要解省空間的話就讓 t2 直接加在 t1 上。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(!t1 && !t2)
            return nullptr;
        //merged_tree = tree1 + tree2

        TreeNode* node = new TreeNode((t1 ? t1->val : 0) + (t2 ? t2->val : 0));
        node->left = mergeTrees((t1)? t1->left : nullptr, (t2)? t2->left : nullptr);
        node->right = mergeTrees((t1)? t1->right : nullptr, (t2)? t2->right : nullptr);
        return node;
    }
};

  目錄