I have the following structure to represent binary tree:
typedef struct node *pnode;
typedef struct node {
int val;
pnode left;
pnode right;
} snode;
Weight of the tree is sum of the val parameter from all nodes of the tree. We say that tree is strongly balanced when it's empty or weight of left equals weight of right subtree and each subtree(left and right) is strongly balanced. I have to write function which tells whether tree is or isn't strongly balanced.
The code I wrote:
int getWeight(pnode tree)
{
if(! tree)
return 0;
return getWeight(tree->left) + getWeight(tree->right)
+ tree->val;
}
bool isStronglyBalanced(pnode tree)
{
if(! tree)
return true;
int wL, wR;
wL = getWeight(tree->left);
wR = getWeight(tree->right);
if(wL != wR)
return false;
return (isStronglyBalanced(tree->left) && isStronglyBalanced(tree->right));
}
The function above does its job pretty good, but I've noticed it's visiting nodes of the tree more than once. Can it be improved (maybe by using dynamic programming) to visit each of the tree's node only once?