leetcode的第617题--合并二叉树,出现了内存对齐的问题?
我的代码如下:
/*
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,
then sum node values up as the new value of the merged node.
Otherwise, the NOT null node will be used as the node of new tree.
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
*/
/**
* 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) {
TreeNode* root;
TreeNode *t1_left, *t1_right;
TreeNode *t2_left, *t2_right;
if (t1 == NULL && t2 == NULL) {
return NULL;
}
else if (t1 != NULL && t2 != NULL) {
root = new TreeNode(t1->val + t2->val);
t1_left = t1->left;
t1_right = t1->right;
t2_left = t2->left;
t2_right = t2->right;
}
else if (t1 != NULL && t2 == NULL) {
root = new TreeNode(t1->val);
t1_left = t1->left;
t1_right = t1->right;
}
else if (t1 == NULL && t2 != NULL) {
root = new TreeNode(t2->val);
t2_left = t2->left;
t2_right = t2->right;
}
root->left = mergeTrees(t1_left, t2_left);
root->right = mergeTrees(t1_right, t2_right);
return root;
}
};
出现了内存对齐的问题。我不清楚是我代码写错了还是其他原因?希望前辈可以解答一下。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Runtime Error
报的错误是运行时错误
(简称RE),有很多原因,常见的有数组越界
,段错误
,访问非法内存
等等。代码整体思路是对的,条件判断这里有些问题,把这一段代码
改为(想想为什么?递归本质是把原问题分为多个小问题)
在这里,不能在递归终止时返回空指针,而应该返回递归结束时的地址给上一层。
稍加修改就可以了