• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
donneyming
博客园    首页    新随笔    联系   管理    订阅  订阅
二叉树(创建、销毁、打印、镜像)

#include <iostream>
using namespace std;

typedef struct bnode
{
 int value;
 bnode* left;
 bnode* right;
}bnode;

#define MAX 7

bnode* head;
void AppendNode(bnode * bn,bnode* h);

bnode* CreateNode()
{
  bnode* bn = (bnode*)malloc(sizeof(bnode));
  if(bn != NULL)
  {
   bn->left =bn->right = NULL;
   return bn;
  }
  else
  {
   cout<<”Error Malloc”<<endl;  
   return NULL;
  }
}

int InitHead()
{
 head = CreateNode();
 if(head == NULL)
  return false;
 else
 {
  head->left =head->right = NULL;
  return true;
 }
}

void  CreateTree(int a[])
{
 head->value =a[0];
 
 for(int i=1;i<MAX ;i++)
 {
  bnode* tree = CreateNode();
  if(tree == NULL)
  {
   return;
  }
  tree->value =a[i];

  AppendNode(tree,head);
 }
}

void AppendNode(bnode * bn,bnode* h)
{
 bnode* ptr = h;
 if(ptr->left == NULL || ptr->right == NULL)
 {
  if(ptr->value > bn->value)
   h->left = bn;

  else
   h->right = bn;
 }
 else if(ptr->value > bn->value)
 {
  AppendNode(bn,ptr->left);
 }
 else
 {
  AppendNode(bn,ptr->right);
 }

 return;
  
}
void PrintTree(bnode* h)
{
 bnode* ptr = h;

 if((ptr->left == NULL)&&(ptr->right == NULL))
 {
  cout<<ptr->value<<endl;
  return;
 }

 if(ptr->left != NULL)
 {
  PrintTree(ptr->left);
 }

 cout<<ptr->value<<endl;
 
 if(ptr->right != NULL)
 {
  PrintTree(ptr->right);
 }
}

void CreateMirro(bnode* h)
{
 bnode* ptr = h;
 bnode* temp ;

 //if(ptr->left != NULL || ptr->right != NULL)
 {
   temp = ptr->left;
   ptr->left = ptr->right;
   ptr->right = temp;
 }
 if(ptr->left != NULL)
 {
  CreateMirro(ptr->left);
 }
 if(ptr ->right != NULL)
 {
  CreateMirro(ptr->right);
 }

 return;

}
void DestoryTree(bnode* h)
{
 bnode* ptr = h;
 bnode *temp;

 if((ptr->left == NULL)&&(ptr->right == NULL))
 {
  temp = ptr;
  free(temp);
  temp = NULL;
  return;
 }

 if(ptr->left != NULL)
 {
  DestoryTree(ptr->left); 
 }
 
 if(ptr->right != NULL)
 {
  DestoryTree(ptr->right);
 }

 temp = ptr;
 free(temp);
 temp = NULL;
}

int main()
{
 int array[7]={10,6,14,4,8,12,16};
 if(false == InitHead())
  return -1;
 CreateTree(array);
 PrintTree(head);
 CreateMirro(head);
 PrintTree(head);
 CreateMirro(head);
 PrintTree(head);
 DestoryTree(head);
 return 0;
}

posted on 2010-11-18 22:10  donneyming  阅读(719)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3