2
votes

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?

1

1 Answers

1
votes

If getweight also told you whether the subtree were strongly-balanced, you could simplify the code to a single scan.

There are a few approaches to returning two pieces of information from a function call. If there were some return value which you knew would never be the weight of a subtree (perhaps a negative number), you could use that as a signal that the subtree was not strongly-balanced. Or you could simply return two values: a bool and an int. (In C, you would use an "out" argument for one of them.) Or you could define a composite object with the two values, which in C would be struct { bool balanced; int weight; }.

However you do it, the logic is the same. In the following pseudo-code, I just assume you can return pairs of values as you can in some languages (C++, for example, but despite any casual similarity, it is still pseudocode):

pair<bool, int> get_weight(tree) {
  if (!tree) return {true, 0};
  balanced, weight_left = get_weight(tree->left);
  if (!balanced) return {false, 0};      /* Returned weight doesn't matter */
  balanced, weight_right = get_weight(tree->right);
  return {balanced && weight_left == weight_right,
          2 * weight_right + tree->val}; /* weight_left == weight_right */
}