40B. Getting the Height of a Node and Full Implementation

A critical issue in keeping a tree height-balanced is how to determine the height of a node. It will not do to compute the height by examining the entire tree, since that costs far to much. We need to get the height of a node very quickly.

To than end, let's store the height of each node in the node. Then all we need to do is be sure to keep the stored height up to date when making changes. Here is the new Node type, along with a function to compute the height of a tree.

  struct Node;
  typedef Node* Tree;
  typedef const Node* ConstTree;

  int height(ConstTree T);

  struct Node
  {
    int   item;      // Information at this node
    int   ht;        // height of this node
    Node* left;      // The left subtree
    Node* right;     // The right subtree

    Node(int it, Node* lft, Node* rgt)
    {
      item  = it;
      left  = lft;
      right = rgt;
      ht    = 1 + max(height(lft), height(rgt));
    }
  };

  //==========================================
  //               height
  //==========================================
  // height(T) returns the height of tree T.
  //
  // Requirement: If T is nonempty, then the
  // ht field has already been set correctly
  // T.
  //==========================================

  int height(ConstTree T)
  {
    if(T == NULL)
    {
      return 0;
    }
    else
    {
      return T->ht;
    }
  }

Implementation

The remaining parts of an implementation of height-balanced binary search trees is available. Look at it if you have questions about how all of these tree operations are be implemented.