题解 | #合并二叉树#
合并二叉树
https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param t1 TreeNode类 * @param t2 TreeNode类 * @return TreeNode类 */ void visit(TreeNode* node1, TreeNode* node2, TreeNode*& node) { if (node1 != nullptr && node2 != nullptr) node->val = node1->val + node2->val; else return; if (node1->left != nullptr && node2->left == nullptr) { node->left = node1->left; } else if (node1->left == nullptr && node2->left != nullptr) { node->left = node2->left; } else if (node1->left == nullptr && node2->left == nullptr) { visit(node1->left, node2->left, node->left); } else { node->left = new TreeNode(0); visit(node1->left, node2->left, node->left); } if (node1->right != nullptr && node2->right == nullptr) { node->right = node1->right; } else if (node1->right == nullptr && node2->right != nullptr) { node->right = node2->right; } else if (node1->right == nullptr && node2->right == nullptr) { visit(node1->right, node2->right, node->right); } else { node->right = new TreeNode(0); visit(node1->right, node2->right, node->right); } } TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { // write code here auto newTree = new TreeNode(0); visit(t1, t2, newTree); return newTree; } };