Skip to content

Instantly share code, notes, and snippets.

@qiaoxu123
Created November 30, 2018 01:17
Show Gist options
  • Save qiaoxu123/58d8569bd60a2496ea5f7f723181c9e2 to your computer and use it in GitHub Desktop.
Save qiaoxu123/58d8569bd60a2496ea5f7f723181c9e2 to your computer and use it in GitHub Desktop.
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, the
/**
* 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){
TreeNode *root = new TreeNode(t1->val + t2->val);
root->left = mergeTrees(t1->left,t2->left);
root->right = mergeTrees(t1->right,t2->right);
return root;
}
else {
return t1 ? t1 : t2;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment