I am working on question to check if Binary structure tree is balanced or not and when I run the code, I get EXC_BAD_ACCESS and I'm not sure how fix problem and what is causing it to break.
The code is suppose to hit NULL and return (true,-1) at some point and go deep into left subtree. Then return and go to right subtree. We can check whether the subtrees of left and right are balanced by different if it is <= 1. and get its height by max(left,right) +1 for each node. if <= 1 means not balance returns (false , height) and it bubbles up to recursion.
Thanks
#include <iostream>
using namespace std;
struct TreeNode {
TreeNode * left;
TreeNode * right;
};
class balanceStatusAndHeight{
public:
bool isBalanced;
int height;
balanceStatusAndHeight(bool isBalanced, int height);
};
balanceStatusAndHeight::balanceStatusAndHeight(bool isBalanced, int height) {
this->isBalanced = isBalanced;
this->height = height;
}
balanceStatusAndHeight checkBalance(TreeNode * root) {
if (root == NULL ) {
return balanceStatusAndHeight(true, -1);
}
balanceStatusAndHeight leftResult = checkBalance(root->left);
if ( !leftResult.isBalanced ) {
return leftResult;
}
balanceStatusAndHeight rightResult = checkBalance(root->right);
if ( !rightResult.isBalanced) {
return rightResult;
}
bool subTreesAreBalanced = abs(leftResult.height - rightResult.height) <= 1;
int height = max(leftResult.height, rightResult.height) + 1;
return balanceStatusAndHeight(subTreesAreBalanced, height);
};
int main(int argc, const char * argv[]) {
TreeNode *a = new TreeNode;
a->left = new TreeNode;
a->left->left = new TreeNode;
balanceStatusAndHeight c = checkBalance(a);
cout << c.isBalanced << endl;
return 0;
}
NULL
, but absolutely no setting variables toNULL
. Don't assume a dynamically allocated object is nicely initialized unless you do it yourself. Add a constructor toTreeNode
toNULL
right
andleft
. – user4581301