2016-08-28 3 views
-3

以下は、セグメント化エラーが発生しているLCAプログラムですが、なぜわかりませんか?LCAプログラムでC++でセグメントエラーが発生する

#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; 
} 
+0

このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –

+1

'else(left?left:right);'? –

答えて

0

障害が

else (left?left:right); 

ので、この線の発生しているセグメントは、このような完全なelse if()elseの文に置き換えます。

else if(left) 
    return left; 
else 
    return right; 
+0

ありがとう!!その実行...どのようにこれが失敗を引き起こしたのか分からないが? – user2737468

関連する問題