给出分段故障错误的c++ LCA程序

LCA program giving Segmented Fault error in C++

本文关键字:c++ LCA 程序 错误 分段 故障      更新时间:2023-10-16

以下是我的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;
}

由于这一行出现分段错误

else (left?left:right);

将其替换为完整的else if()else语句,如下所示。

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