一、题目说明
题目617. Merge Two Binary Trees,合并两个二叉树。难度是Easy!
二、我的解答
这个题目,用递归解法非常简单,同二叉树的递归遍历。
class Solution{
public:
TreeNode* mergeTrees(TreeNode* t1,TreeNode* t2){
if(t1==NULL) return t2;
if(t2==NULL) return t1;
int cur = t1->val + t2->val;
TreeNode* root = new TreeNode(cur);
root->left = mergeTrees(t1->left,t2->left);
root->right = mergeTrees(t1->right,t2->right);
return root;
}
};
性能如下:
Runtime: 52 ms, faster than 46.21% of C++ online submissions for Merge Two Binary Trees.
Memory Usage: 26.1 MB, less than 5.55% of C++ online submissions for Merge Two Binary Trees.
三、优化措施
非递归算法就不写了。