与二叉树有关的一些操作:先序,中序,后序,层次遍历,计算深度,叶结点数

来源:互联网 发布:云计算概念股龙头 编辑:程序博客网 时间:2024/04/27 22:14

//先序遍历
template <typename T>
void preorderOutput(tnode<T> *t, const string& separator = "  ")
{
   // the recursive scan terminates on a empty subtree
   if (t != NULL)
   {
      cout << t->nodeValue << separator; // output the node
       inorderOutput(t->left, separator);      // descend left
       inorderOutput(t->right, separator);   // descend right
   }
}

//中序遍历
template <typename T>
void inorderOutput(tnode<T> *t, const string& separator = "  ")
{
   // the recursive scan terminates on a empty subtree
   if (t != NULL)
   {
      inorderOutput(t->left, separator); // descend left
      cout << t->nodeValue << separator; // output the node
      inorderOutput(t->right, separator); // descend right
   }
}

//后序遍历
template <typename T>
void postorderOutput(tnode<T> *t, const string& separator = "  ")
{
   // the recursive scan terminates on a empty subtree
   if (t != NULL)
   {
      postorderOutput(t->left, separator); // descend left
      postorderOutput(t->right, separator); // descend right
      cout << t->nodeValue << separator;   // output the node
   }
}

//层次遍历
template <typename T>
void levelorderOutput(tnode<T> *t, const string& separator = "  ")
{
   // store siblings of each node in a queue so that they are
   // visited in order at the next level of the tree
   queue<tnode<T> *> q;
   tnode<T> *p;

   // initialize the queue by inserting the root in the queue
   q.push(t);

   // continue the iterative process until the queue is empty
   while(!q.empty())
   {
      // delete front node from queue and output the node value
      p = q.front();
  q.pop();
      cout << p->nodeValue << separator;

  // if a left child exists, insert it in the queue
      if(p->left != NULL)
   q.push(p->left);
      // if a right child exists, insert next to its sibling
      if(p->right != NULL)
   q.push(p->right);
   }
}

//计算叶结点数
// assume that count initialized to 0
template <typename T>
void countLeaf (tnode<T> *t, int& count)
{
   if (t != NULL)
   {
      // check if t is a leaf node (no children).
      // if so, increment count
      if (t->left == NULL && t->right == NULL)
         count++;

  countLeaf(t->left, count);  // descend left
  countLeaf(t->right, count); // descend right
   }
}

//计算树的深度,空树深度设为-1
// determine the depth of the tree using a postorder scan
template <typename T>
int depth (tnode<T> *t)
{
   int depthLeft, depthRight, depthval;

   if (t == NULL)
  // depth of an empty tree is -1
   depthval = -1;
   else
 {
  // find the depth of the left subtree of t
  depthLeft= depth(t->left);
  // find the depth of the right subtree of t
  depthRight= depth(t->right);
  // depth of the tree with root t is 1 + maximum
  // of the depths of the two subtrees
  depthval = 1 +
   (depthLeft > depthRight ? depthLeft : depthRight);
   }

 return depthval;
}

原创粉丝点击