【发布时间】:2016-08-28 09:29:11
【问题描述】:
以下是我的 LCA 程序,它给出了分段错误错误,但我不明白为什么?
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* left, *right;
};
struct node* lca(struct node* root, int n1, int n2){
struct node* left,*right;
if (root == NULL) return root;
if (root->data == n1 || root->data == n2)
return root;
left = lca(root->left,n1,n2);
right = lca(root->right,n1,n2);
if(left && right)
return root;
else (left?left:right);
}
struct node* newNode(int data){
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
int main(void){
struct node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
int n1 = 10, n2 = 14;
struct node *t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 14, n2 = 8;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 10, n2 = 22;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
getchar();
return 0;
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
else (left?left:right);?