# Leetcode 617. Merge Two Binary ###### tags: `Leetcode` 題目 You are given two binary trees root1 and root2. 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 the two trees 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 the new tree. Return the merged tree. Note: The merging process must start from the root nodes of both trees. 解法: 1.用遞迴解,若不是兩個root同時為NULL,就新建一個Node,這邊會額外再建一個tree,因此多消耗了記憶體空間 2.直接把其中一個tree當作最後要回傳的,就可節省一點空間 1. ``` /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2){ if(root1 == NULL && root2 == NULL) return NULL; struct TreeNode* Node = calloc(1,sizeof(struct TreeNode)); if(root1 != NULL) Node->val+=root1->val; if(root2 != NULL) Node->val+=root2->val; struct Node* t1Left = (root1 == NULL ? NULL : root1->left); struct Node* t2Left = (root2 == NULL ? NULL : root2->left); Node->left = mergeTrees(t1Left, t2Left); struct Node* t1right = (root1 == NULL ? NULL : root1->right); struct Node* t2right = (root2 == NULL ? NULL : root2->right); Node->right = mergeTrees(t1right, t2right); /* 這邊是原本寫的一大串,可改成上面那一段,縮短成6行 if(root1 == NULL) { Node->left = mergeTrees(NULL, root2->left); Node->right = mergeTrees(NULL, root2->right); } else if(root2 == NULL) { Node->left = mergeTrees(root1->left, NULL); Node->right = mergeTrees(root1->right, NULL); } else { Node->left = mergeTrees(root1->left, root2->left); Node->right = mergeTrees(root1->right, root2->right); } */ return Node; } ``` 2. ``` /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2){ if(root1 == NULL) return root2; else if(root2 == NULL) return root1; else { root1->val+=root2->val; root1->left = mergeTrees(root1->left, root2->left); root1->right = mergeTrees(root1->right, root2->right); } return root1; } ```