BM32. 合并二叉树
描述
示例1
输入:
{1,3,2,5},{2,1,3,#,4,#,7}
输出:
{3,4,5,5,4,#,7}
说明:
如题面图示例2
输入:
{1},{}
输出:
{1}
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2020-12-20
class Solution { public: /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) { // write code here if (t1 == nullptr && t2 == nullptr) return nullptr; else if (t1 == nullptr) return t2; else if (t2 == nullptr) return t1; else { TreeNode *t = new TreeNode(t1->val + t2->val); t->left = mergeTrees(t1->left, t2->left); t->right = mergeTrees(t1->right, t2->right); return t; } } };
C++ 解法, 执行用时: 2ms, 内存消耗: 380KB, 提交时间: 2021-07-18
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { // write code here if(!t1) return t2; if(!t2) return t1; t1->val += t2->val; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 380KB, 提交时间: 2021-07-13
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if(!t1 && !t2) return nullptr; TreeNode *tmp = new TreeNode(-1); tmp->val = (t1?t1->val:0) + (t2?t2->val:0); tmp->left = mergeTrees(t1?t1->left:nullptr, t2?t2->left:nullptr); tmp->right = mergeTrees(t1?t1->right:nullptr, t2?t2->right:nullptr); return tmp; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 380KB, 提交时间: 2021-07-13
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if(!t1)return t2; if(!t2)return t1; t1->val+=t2->val; t1->left=mergeTrees(t1->left, t2->left); t1->right=mergeTrees(t1->right, t2->right); return t1; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 384KB, 提交时间: 2021-07-10
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ TreeNode* dfs(TreeNode* t1, TreeNode* t2) { TreeNode* ans; if(t1==nullptr&&t2==nullptr) return nullptr; if(t1==nullptr) ans=new TreeNode(t2->val); else if(t2==nullptr) ans=new TreeNode(t1->val); else ans=new TreeNode(t2->val+t1->val); ans->left=dfs((t1==nullptr)?nullptr:t1->left,(t2==nullptr)?nullptr:t2->left); ans->right=dfs((t1==nullptr)?nullptr:t1->right,(t2==nullptr)?nullptr:t2->right); return ans; } TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { // write code here return dfs(t1,t2); } };