这道题想了很久,并没有掌握思想,写了很多,也没有解决。先贴出思考的过程。
class Solution { public: vector<TreeNode> v1; vector<TreeNode> v2; queue<TreeNode> Q1; queue<TreeNode> Q2; void FloorTree(TreeNode tree, int type) { TreeNode node = TreeNode(tree.val); node.left = tree.left; node.right = tree.right; if (type == 1) { Q1.push(node); while (!Q1.empty()) { TreeNode livenode = TreeNode(0); livenode = Q1.front(); Q1.pop(); v1.push_back(livenode); if (&livenode != NULL && (livenode.left != NULL || livenode.right != NULL)) { if (livenode.left != NULL) { Q1.push(*livenode.left); } else { TreeNode node = TreeNode(0); Q1.push(node); } if (livenode.right != NULL) { Q1.push(*livenode.right); } else { TreeNode node = TreeNode(0); Q1.push(node); } } } } else { Q2.push(node); while (!Q2.empty()) { TreeNode livenode = TreeNode(0); livenode = Q2.front(); Q2.pop(); v2.push_back(livenode); if (&livenode != NULL && (livenode.left != NULL || livenode.right != NULL)) { if (livenode.left != NULL) { Q2.push(*livenode.left); } else { TreeNode node = TreeNode(0); Q2.push(node); } if (livenode.right != NULL) { Q2.push(*livenode.right); } else { TreeNode node = TreeNode(0); Q2.push(node); } } } } } TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { FloorTree(*t1, 1); FloorTree(*t2, 2); int len1 = v1.size(); int len2 = v2.size(); vector<TreeNode> V; if (len1 <= len2) { for (int i = 0; i < len1; i++) { TreeNode t1 = v1[i]; TreeNode t2 = v2[i]; t1.val += t2.val; V.push_back(t1); } for (int i = len1; i < len2; i++) { TreeNode t = v2[i]; V.push_back(t); } } else { for (int i = 0; i < len2; i++) { TreeNode t1 = v1[i]; TreeNode t2 = v2[i]; t2.val += t1.val; V.push_back(t2); } for (int i = len2; i < len1; i++) { TreeNode t = v1[i]; V.push_back(t); } } for (int i = 0; i < V.size(); i++) { } TreeNode* N = NULL; return N; } };
下面列出正确的解法。
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (t1 == NULL)return t2; if (t2 == NULL)return t1; t1->val += t2->val; t1->left = mergeTrees(t1->left, t2->left); t1->right = mergeTrees(t1->right, t2->right); return t1; }
补充一个python的实现,和上面的C++的思路基本一样,只是我个人感觉更容易理解一些:
1 class Solution: 2 def mergeTrees(self, t1: 'TreeNode', t2: 'TreeNode') -> 'TreeNode': 3 if t1!=None or t2!=None: 4 if t1==None: 5 t1 = TreeNode(0) 6 if t2==None: 7 t2 = TreeNode(0) 8 t = TreeNode(0) 9 t.val = t1.val + t2.val 10 t.left = self.mergeTrees(t1.left,t2.left) 11 t.right = self.mergeTrees(t1.right,t2.right) 12 return t 13 14 return None