【问题标题】:LCA program giving Segmented Fault error in C++LCA 程序在 C++ 中给出分段错误错误
【发布时间】: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;
}

【问题讨论】:

标签: c++ tree


【解决方案1】:

由于这条线而发生分段错误

else (left?left:right);

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

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

【讨论】:

  • 谢谢!!它正在运行...虽然我不明白这是如何导致失败的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
相关资源
最近更新 更多