二叉树(创建、销毁、打印、镜像)

本文提供了一个使用C++实现的二叉树基本操作示例,包括创建节点、添加节点、打印树结构、创建镜像树及销毁树等。通过具体的代码展示了如何构造一个简单的二叉树,并进行相关操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

转载于:https://www.cnblogs.com/donneyming/archive/2010/11/18/1881253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值