C++,二叉树的高度,我没有检查我的子树是否为空,而是检查我的子树是否为叶节点。抛出分段错误
C++, Height of Binary Tree, Instead of Checking if my subtree is empty I am checking if my subtree is a leaf node. Throws Segmentation fault
代码 1
int height(Node* root) {
if(root==NULL)
return -1;
else
return max(height(root->left),height(root->right))+1;
}
代码 2
int height(Node* root) {
if(root->left==NULL and root->right==NULL)
return 0;
else
return max(height(root->left),height(root->right))+1;
}
代码 1 给出了正确答案,而代码 2 抛出分段错误。根据我的说法,代码 2 中的逻辑是正确的,因为我没有检查空树并返回 -1,而是检查叶节点并返回 0。
谁能解释一下分段错误到底是什么,为什么会出现在我的代码中?
根据您所说的(即:"Code 1 gives me the correct answer"),root
显然是一个 nullptr,因此尝试通过 root->left
取消引用它会导致未定义的行为。
代码 1
int height(Node* root) {
if(root==NULL)
return -1;
else
return max(height(root->left),height(root->right))+1;
}
代码 2
int height(Node* root) {
if(root->left==NULL and root->right==NULL)
return 0;
else
return max(height(root->left),height(root->right))+1;
}
代码 1 给出了正确答案,而代码 2 抛出分段错误。根据我的说法,代码 2 中的逻辑是正确的,因为我没有检查空树并返回 -1,而是检查叶节点并返回 0。 谁能解释一下分段错误到底是什么,为什么会出现在我的代码中?
根据您所说的(即:"Code 1 gives me the correct answer"),root
显然是一个 nullptr,因此尝试通过 root->left
取消引用它会导致未定义的行为。