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.
這道題給了兩個二叉樹,讓我們合並成一個,規則是,都存在的結點,就將結點值加起來,否則空的位置就由另一個樹的結點來代替。那么根據過往經驗,處理二叉樹問題的神器就是遞歸。根據題目中的規則,如果要處理的相同位置上的兩個結點都不存在的話,直接返回即可,如果 t1 存在,t2 不存在,就以 t1 的結點值建立一個新結點,然后分別對 t1 的左右子結點和空結點調用遞歸函數,反之,如果 t1 不存在,t2 存在,就以 t2 的結點值建立一個新結點,然后分別對 t2 的左右子結點和空結點調用遞歸函數。如果 t1 和 t2 都存在,就以 t1 和 t2 的結點值之和建立一個新結點,然后分別對 t1 的左右子結點和 t2 的左右子結點調用遞歸函數,參見代碼如下:
解法一:
class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { TreeNode *res = NULL; helper(t1, t2, res); return res; } void helper(TreeNode* t1, TreeNode* t2, TreeNode*& res) { if (!t1 && !t2) return; else if (t1 && !t2) { res = new TreeNode(t1->val); helper(t1->left, NULL, res->left); helper(t1->right, NULL, res->right); } else if (!t1 && t2) { res = new TreeNode(t2->val); helper(NULL, t2->left, res->left); helper(NULL, t2->right, res->right); } else { res = new TreeNode(t1->val + t2->val); helper(t1->left, t2->left, res->left); helper(t1->right, t2->right, res->right); } } };
其實遠不用寫的像上面那么復雜,連額外的函數都不用寫,直接遞歸調用給定的函數即可,首先判斷,如果 t1 不存在,則直接返回 t2,反之,如果 t2 不存在,則直接返回 t1。如果上面兩種情況都不滿足,那么以 t1 和 t2 的結點值之和建立新結點t,然后對 t1 和 t2 的左子結點調用遞歸並賦給t的左子結點,再對 t1 和 t2 的右子結點調用遞歸並賦給t的右子結點,返回t結點即可,參見代碼如下:
解法二:
class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (!t1) return t2; if (!t2) return t1; TreeNode *t = new TreeNode(t1->val + t2->val); t->left = mergeTrees(t1->left, t2->left); t->right = mergeTrees(t1->right, t2->right); return t; } };
Github:
https://github.com/grandyang/leetcode/issues/617
參考資料:
https://leetcode.com/problems/merge-two-binary-trees/