[英]Having issues on pointers for a c program
I write the code that intends to perform an in-order traverse of a binary search tree and find the minimum absolute difference between values of any two nodes. 我编写了打算对二进制搜索树进行有序遍历的代码,并找到了任意两个节点的值之间的最小绝对差。 I write this code and when I run this test case, instead of returning result 1, it throws result 2. 我编写了这段代码,当我运行此测试用例时,它没有返回结果1,而是抛出了结果2。
Here is the test case: 这是测试用例:
2
/ \
1 4
Here is the code that I write: 这是我编写的代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void inOrder(struct TreeNode* temp1, struct TreeNode* temp2, int* result) {
if (temp1->left != NULL) {
inOrder(temp1->left, temp2, result);
}
if (temp2 != NULL) {
int dif = temp1 -> val - temp2 -> val;
*result = *result > dif ? dif : *result;
}
printf("%p\n", temp2);
temp2 = temp1;
if (temp1->right != NULL) {
inOrder(temp1->right, temp2, result);
}
}
int getMinimumDifference(struct TreeNode* root) {
int result = 0x7fffffff;
struct TreeNode* temp = NULL;
inOrder(root, temp, &result);
return result;
}
Here is the output of the printf: 这是printf的输出:
(nil)
(nil)
0xfe72b0
As you can see, only the last node is not null. 如您所见,只有最后一个节点不为空。 Which is abnormal since based on the logic of the code there should be two non-null printings. 这是异常的,因为根据代码的逻辑,应该有两次非空打印。
So could you please help me solve this bug? 那你能帮我解决这个错误吗?
In your code temp2
is always NULL. 在您的代码中temp2
始终为NULL。
Try below snippet 尝试以下代码段
void inOrder(struct TreeNode* temp1, struct TreeNode* temp2, int* result) {
if (temp1->left != NULL) {
inOrder(temp1->left, temp1, result);
}
if (temp2 != NULL) {
int dif = temp1 -> val - temp2 -> val;
if(dif < 0) dif *= -1; //absolute diff
*result = *result > dif ? dif : *result;
}
printf("%p\n", temp2);
//temp2 = temp1;
if (temp1->right != NULL) {
inOrder(temp1->right, temp1, result);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.