binary tree complete check
Ok, I'm working on a binary tree class that needs to have a member function that determines if the tree is complete. The tree is complete if it's balanced and all the nodes on the bottom level are on the left. The tree is balanced if the bottom nodes are no more than one level away from each other. I made this to check if the tree is balanced:
Code:
bool tree_t::isbalanced() {
if (root == NULL)
return true;
else
return onisbalanced(root,1,getnumlevels());
}
bool tree_t::onisbalanced(node_t* node, int level, int numlevels) {
return (node->left != NULL &&
onisbalanced(node->left,level+1,numlevels)) &&
(node->right != NULL &&
onisbalanced(node->right,level+1,numlevels)) &&
!(node->left == NULL &&
node->right == NULL && level < numlevels - 1);
}
This runs through all the nodes recursively and checks that only nodes at the bottom two levels can have no children. This seems like it should work fine to me, but it always says that the tree is unbalanced. I get the feeling there's a really simple way to do this that I'm missing, or maybe I just have some basic logic flaw.