二叉樹的基本操作和遍歷

2021-07-02 17:30:19 字數 2205 閱讀 8456

下面將介紹二叉樹的基本操作和先序中序後序遍歷

先看看二叉樹基本定義:

typedef char data;//定義元素型別

typedef struct chaintree//定義二叉樹結點型別

chainbintree;

//初始化二叉樹

chainbintree *chainbintreeinit(chainbintree *node)

int chainbintreeaddnode(chainbintree *bt,chainbintree*node,int n)

//新增資料到二叉樹

//bt為父結點,node為子結點,n=1表示新增左子樹,n=2表示新增右子樹

switch(n)

else

case 2://新增到右結點

if(bt->right)//右子樹不為空

else

default:

printf("引數錯誤");

return 0;

}}//返回左結點

chainbintree *chainbintreeleft(chainbintree *bt)

else

return null;

}//返回右結點

chainbintree *chainbintreeright(chainbintree *bt)

else

return null;

}//檢查二叉樹是否為空,為空則返回1,否者返回0;

int chainbintreeempty(chainbintree *bt)

else

return 1;

}//求二叉樹深度

int chainbintreedepth(chainbintree *bt)

else

} //在二叉樹中查詢值為data的結點

chainbintree *chainbintreefind(chainbintree *bt,data data)

else

}} //清空二叉樹

void chainbintreeclear(chainbintree *bt)

return ;

} //先序遍歷

void chainbintree_dlr(chainbintree *bt,void(*oper)(chainbintree *p)) }

//中序遍歷

void chainbintree_dlr1(chainbintree *bt,void(*oper)(chainbintree *p)) }

//後序遍歷

void chainbintree_dlr2(chainbintree *bt,void(*oper)(chainbintree *p))

}然後測試

#include "stdio.h"

#include "chainbintree.c"

void oper(chainbintree *p)

chainbintree *initroot()//初始化二叉樹的根

return null;

}void addnode(chainbintree *bt)

printf("1,新增到左子樹\n2.新增到右子樹");

do

} while(select!=1 &&select!=2) ;

}return;

} int main()

}while(select!=0);

chainbintreeclear(root);

root = null;

while(1);

return 0 ;

}

按下圖的順序依次插入結點最後達到目的:

二叉樹的基本遍歷

define crt secure no warnings include include includestruct binnode 先序遍歷 根左右 void xianxubianli struct binnode root printf c root ch 遞迴遍歷左子樹 xianxubian...

二叉樹基本操作 二叉樹的建立與遞迴遍歷

建立的二叉樹如下 來構建上圖的二叉樹 詳細 如下 include using namespace std typedef char datatype 二叉樹的左右鏈表示,也叫做二叉鍊錶表示 typedef struct node node typedef node btree btree precr...

二叉樹的遍歷操作

include include includeusing namespace std 定義二叉樹的節點資料型別 struct btnode class binarytree 建構函式,將根節點置空 binarytree 銷毀二叉樹 void createbtree 層次遍歷二叉樹 演算法概述 層次遍...