c++: almost same input but 2nd call shows segment fault -
i've been c# developer long time , seek refresh previous c++ knowledge. don't know why "root" address of sec isbalanced(root) phone call becomes 0x0. definitely, question obvious c++ developers. please, provide me hint.
the result: 1. balanced? 0 segmentation fault: 11
#include <iostream> using namespace std; struct node { node* left; node* right; }; int getheight(node *node) { if(node == null) homecoming 0; if(node->left == null && node->right == null) homecoming 1; int leftheight = getheight(node->left); int rightheight = getheight(node->right); if(leftheight > rightheight) homecoming 1 + leftheight; else homecoming 1 + rightheight; } bool isbalanced(node &node){ int leftheight = 0; int rightheight = 0; if(node.left == null && node.right == null) homecoming true; if(node.left != null) leftheight = getheight(node.left); if(node.right != null) rightheight = getheight(node.right); int diff = leftheight - rightheight; if(diff >= -1 && diff <= 1) { if(isbalanced(*node.left) && isbalanced(*node.right)) homecoming true; else homecoming false; } else homecoming false; } int main() { node root, n1, n2, n3, n4, n5; root.left = &n1; root.right = null; n1.left = &n2; n1.right = &n3; n2.left = null; n2.right = null; n3.left = &n4; n3.right = null; n4.right = &n5; n4.left = null; n5.right = null; n5.left = null; cout<< "1. balanced? " << isbalanced(root) << endl; root.left = &n1; root.right = &n2; n1.left = &n3; n1.right = &n4; n2.left = &n5; n2.right = null; n3.left = null; n3.right = null; n4.right = null; n4.left = null; n5.right = null; n5.left = null; cout<< "2. balanced? " << isbalanced(root) << endl; homecoming 0; }
this line culprit.
if(isbalanced(*node.left) && isbalanced(*node.right))
you not checking whether node.left
or node.right
null before dereferencing them. first iteration works due lucky coincidence.
here's updated version of isbalanced
works me:
bool isbalanced(node &node){ int leftheight = 0; int rightheight = 0; if(node.left == null && node.right == null) homecoming true; if(node.left != null) leftheight = getheight(node.left); if(node.right != null) rightheight = getheight(node.right); int diff = leftheight - rightheight; if(diff >= -1 && diff <= 1) { if ( node.left == null || node.right == null ) { homecoming true; } else { homecoming (isbalanced(*node.left) && isbalanced(*node.right)); } } else homecoming false; }
c++
No comments:
Post a Comment