二叉树的创建,遍历和释放

来源:互联网 发布:外国人吃燕窝吗 知乎 编辑:程序博客网 时间:2024/05/19 12:11

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

// 先序遍历二叉树,把所有节点都用空节点填充
// 用+表示空节点
static char * str = "AB+C+D++EF++GH+IJ++++";

// 二叉树节点结构
typedef struct tag_BinTree
{
  char value;
  struct tag_BinTree * left;
  struct tag_BinTree * right;
 
  tag_BinTree()
  {
    value = 0x00;
 left = 0;
 right = 0;
  }
}BinTree;

// 创建二叉树
void createBinTree(BinTree * & node)
{
  static int counter = 0;
  if (counter >= strlen(str) || str[counter] == '+' || !isalpha(str[counter]))
  {
    if (str[counter] == '+')
    {
      counter ++;
    }
    return;
  }
  else
  {
    node = new BinTree;
    node->value = str[counter];
    counter ++;

    createBinTree(node->left);
    createBinTree(node->right);
  }
}

// 中序遍历,打印二叉树
void dumpBinTree(BinTree * root)
{
  if (root)
  {
    dumpBinTree(root->left);
    printf("%c " , root->value);
    dumpBinTree(root->right);
  }
  else
  {
    return;
  }
}

// 后序遍历释放二叉树
void destroyBinTree(BinTree * root)
{
  if (root)
  {
    destroyBinTree(root->left);
    destroyBinTree(root->right);

    delete root;
    root = 0;
  }
}