您的位置:首页 > 其它

load of misaligned address 0x000000835093 for type 'int'

2018-03-30 13:33 435 查看
530. Minimum Absolute Difference in BSTGiven a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.Example:Input:

1
\
3
/
2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
按照深度优先搜索,可以得到从大到小的排列:3,2,1.难点是,1. 3怎么办?他没有比他大的。2. 第一个差值怎么办,没有差值。

问题1:load of misaligned address 0x000000835093 for type 'int'/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int getMinimumDifference(struct TreeNode* root) {
int md=0, next=0;
struct TreeNode *Max = root;
while(NULL != (Max->right)) Max = Max->right;
process(root, Max, &next, &md);
return md;
}

void process(struct TreeNode* root, struct TreeNode* Max, int *next, int *md){
if(NULL != root){
process(root->right, Max, md, next);
if(root == Max) {
*md = *next = root->val;
}else{
int a1, a2;
a1= root->val;
a2 = (*next);
if(*md - (a1-a2) < 0)
*md = a1 - a2;
}
next = root->val;
process(root->left, Max, md, next);
}
}居然出现了指针不对齐的问题,一查都是,什么指针结构体里很多个指针,出现内存不对齐,显然没用。
经过一上午,发现:
next = root->val;倒数第4行忘了加*。——解决方案:1.把例子在大脑里走一遍。 2. 在本地调试。
问题2:边界条件int getMinimumDifference(struct TreeNode* root) {
int md, bigger;
struct TreeNode *Max = root, *Min = root;
while(NULL != (Max->right)) Max = Max->right;
while(NULL != (Min->left)) Min = Min->left;
md = Max->val - Min->val;
bigger = Max->val + md;
process(root, &bigger, &md);
return md;
}

void process(struct TreeNode* root, int *bigger, int *md){
if(NULL != root){
process(root->right, bigger, md);
if(*md > *bigger-root->val)
*md = *bigger-root->val;
*bigger = root->val;
process(root->left, bigger, md);
}
}1. 把md设置成max-min,得到了最大差值。因为题目保证了,最少有两个节点。
2. 去掉了最大节点指针,这里的bigger的设置成了问题,想法是bigger-root->val = md,显然bigger有可能越界。
回头再分析一下越界会不会带来问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐