gpt4 book ai didi

c++ - 当我声明 root->right->right = newnode(7);评论,编译器显示运行时错误。谁能解释为什么?

转载 作者:行者123 更新时间:2023-11-28 01:55:40 24 4
gpt4 key购买 nike

我正在用 C++ 编写计算二叉树中根到叶路径总数的代码。

#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
struct node
{int data;
struct node *left;
struct node *right;
};

struct node* newnode(int data)
{struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}

int root_to_leaf_paths(struct node *root)
{if(root->left == NULL && root->right == NULL)
return 1;
else if(root == NULL)
return 0;
else
return(root_to_leaf_paths(root->left)+root_to_leaf_paths(root->right));

}

int main()
{
struct node *root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
root->right->left = newnode(6);

当我添加以下行注释时,编译器显示运行时错误。

 **//root->right->right = newnode(7);**  

printf("%d",root_to_leaf_paths(root));
}

最佳答案

条件的顺序是倒序的:

 if(root->left == NULL && root->right == NULL)  
return 1;
else if(root == NULL)
return 0;
else
return(root_to_leaf_paths(root->left)+root_to_leaf_paths(root->right));

在访问root->left 等之前,您需要先确定root 不为空

关于c++ - 当我声明 root->right->right = newnode(7);评论,编译器显示运行时错误。谁能解释为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com