1. 程式人生 > >[LeetCode] Merge Two Binary Trees 合並二叉樹

[LeetCode] Merge Two Binary Trees 合並二叉樹

滿足 values bin pro per ive sum solution rand

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;
    }
};

參考資料:

https://discuss.leetcode.com/topic/92105/java-solution-6-lines-tree-traversal

https://discuss.leetcode.com/topic/92222/runtime-beat-100-6-lines-java-recursive-solution

LeetCode All in One 題目講解匯總(持續更新中...)

[LeetCode] Merge Two Binary Trees 合並二叉樹