# 数据结构之二叉树的基本操作

binarytree.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
typedef char treenodetype;
typedef struct treenode{
treenodetype data;
struct treenode *lchild;
struct treenode *rchild;
}treenode;
void treenode_Init(treenode **root);//初始化二叉树
void treenode_PreOrder(treenode *root);//先序遍历
void treenode_InOrder(treenode *root);//中序遍历
void treenode_PostOrder(treenode *root);//后序遍历
void treenode_LevelOrder(treenode *root);//层序遍历
treenode *_treecreat(treenodetype data[],size_t size,size_t *index,treenodetype null_node);
treenode *_treeCreat(treenodetype data[],size_t size,char null_node);
treenode * treenode_clone(treenode *root);
size_t treeleafsize(treenode *root);
size_t treeKlevelsize(treenode *root,int k);
size_t treehight(treenode *root);
treenode *treefind(treenode *root,treenodetype to_find);
void PreOrderByLoop(treenode *root);
void InOrderByLoop(treenode *root);
void PostOrderByLoop(treenode *root);
void TreeMirror(treenode *root);


#include <unistd.h>
#include<string.h>
#include<math.h>
#include "binarytree.h"
#include "seqqueue.h"
#include "seqqueue.c"
#include "seqstack.c"
#include "seqstack.h"

void treenode_Init(treenode **root)
{
if(root == NULL)
{
return;
}
*root = NULL;
return;
}


treenode* treenode_creatnode(treenodetype value)
{

treenode *newnode = (treenode *)malloc(sizeof(treenode));
newnode->data = value;
newnode->lchild = NULL;
newnode->rchild = NULL;
return newnode;
}


void treenode_PreOrder(treenode *root)
{
if(root == NULL)
{
return;
}
printf("[%c] ",root->data);
treenode_PreOrder(root->lchild);
treenode_PreOrder(root->rchild);
}



void treenode_InOrder(treenode *root)
{
if(root == NULL)
{
return;
}
treenode_InOrder(root->lchild);
printf("[%c] ",root->data);
treenode_InOrder(root->rchild);
}


void treenode_PostOrder(treenode *root)
{
if(root == NULL)
{
return;
}
treenode_PostOrder(root->lchild);
treenode_PostOrder(root->rchild);
printf("[%c] ",root->data);

}


void treenode_LevelOrder(treenode *root)
{
if(root == NULL)
{
return;
}
seqqueue queue;
seqqueue_init(&queue);
seqqueue_push(&queue,root);
while(1)
{
seqqueuetype top;
int ret = seqqueue_gettop(&queue,&top);
//printf("top data is %c, top lchild %p,queue size is %lu\n",top->data, top->lchild,queue.size);

if(ret == 0)
{
break;
}
printf("[%c] ",top->data);
seqqueue_pop(&queue);
if(top->lchild != NULL)
{
seqqueue_push(&queue,top->lchild);
}
if(top->rchild != NULL)
{
seqqueue_push(&queue,top->rchild);
}
}
}


• 评论

• 下一篇
• 上一篇