Balance is defined as no two nodes has greater than one height.
Code:
use queue.size() to remember how many nodes at each layer (height)
// Iterative method to find height of Bianry Treeint treeHeight(node *root){ // Base Case if (root == NULL) return 0; // Create an empty queue for level order tarversal queue q; // Enqueue Root and initialize height q.push(root); int height = 0; while (1) { // nodeCount (queue size) indicates number of nodes // at current lelvel. int nodeCount = q.size(); if (nodeCount == 0) return height; height++; // Dequeue all nodes of current level and Enqueue all // nodes of next level while (nodeCount > 0) { node *node = q.front(); q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } }}Following method is to determine whether it is balanced
int checkheight(TreeNode* root)
{
if (!root) return 0;
int leftheight = checkheight(root->left);
if (leftheight==-1) return -1;
int rightheight = checkheight(root->right);
if (rightheight==-1) return -1;
int heightDiff = leftheight-rightheight;
if ( abs(heightDiff) >1 )
return -1;
else
return max(leftheight, rightheight) +1;
}
// check whether its is balanced tree
bool balancecheck(TreeNode* root)
{
if(checkheight(root) == -1 )
return false;
else
return true;
}
No comments:
Post a Comment