当我做出语句 root->right->right = newnode(7);注释,编译器显示运行时错误。谁能解释为什么?

When I make the statement root->right->right = newnode(7); a comment, the compiler shows a runtime error.Can anyone explain why?

本文关键字:gt 显示 编译器 注释 运行时错误 为什么 能解释 newnode 语句 root- right-      更新时间:2023-10-16

我正在编写用于计算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在访问root->left等之前不是null。