c语言树作用,C语言之树学习

概念:

T: Tree

树形表示法

嵌套集合表示法

凹入表表示法

广义表表示法

Degree:

节点子树的个数

BT: Binary Tree

每个节点最多有两个孩子

BST:Binary Search Tree

每个节点最多有两个孩子

每个节点的值比它左子树的所有节点的值都要大

每个节点的值比它右子树的所有节点的值都要小

树的性质:

0818b9ca8b590ca3270a3433284dd417.png

BST数组实现:

根节点是第一个节点,数组下标1

节点N的双亲:N/2

节点N的左孩子:2N

节点N的右孩子:2N + 1

根节点第0个节点,数组下标0

节点N的双亲:(N + 1) / 2 -1

节点N的左孩子:2N + 1

节点N的右孩子:2N + 2

code

#include

#include

#define BST_SIZE 100

#define BST_ARRAY_SIZE BST_SIZE + 1

#define BST_DEFAULT_VALUE 0

static int auiBST[BST_ARRAY_SIZE];

#define LEFT_INDEX(iCurIdx) \

(iCurIdx * 2)

#define RIGHT_INDEX(iCurIdx) \

((iCurIdx) * 2 + 1)

#define BST_ARRAY_INIT() \

{ \

int iIdx = 0; \

for (iIdx = 0; iIdx < BST_ARRAY_SIZE; iIdx++) \

{ \

auiBST[iIdx] = BST_DEFAULT_VALUE; \

} \

}

#define BST_ARRAY_DISPLAY() \

{ \

int iIdx = 0; \

for (iIdx = 0; iIdx < BST_ARRAY_SIZE; iIdx++) \

{ \

printf("%d ", auiBST[iIdx]); \

if (0 == ((iIdx + 1) % 16)) \

{ \

printf("\r\n"); \

} \

} \

printf("\r\n"); \

}

#define BST_CURVALUE(iCurIdx) \

auiBST[iCurIdx]

#define BST_SETVALUE(iCurIdx, iNum) \

auiBST[iCurIdx] = iNum;

int BST_Insert(int iNum)

{

int iCurIdx = 1;

int iRet = 0;

assert(iNum > 0);

while (BST_CURVALUE(iCurIdx) != BST_DEFAULT_VALUE)

{

if (BST_CURVALUE(iCurIdx) > iNum)

{

iCurIdx = LEFT_INDEX(iCurIdx);

}

else if(BST_CURVALUE(iCurIdx) < iNum)

{

iCurIdx = RIGHT_INDEX(iCurIdx);

}

else

{

printf("CurIdx :%d Value :%d The value already exist.\r\n", iCurIdx, iNum);

break;

}

if (iCurIdx > BST_ARRAY_SIZE)

{

printf("The array size is not enough, CurIdx: %d.\r\n", iCurIdx);

iRet = -1;

break;

}

}

if (iRet != -1)

{

printf("CurIdx :%d Value :%d\r\n", iCurIdx, iNum);

BST_SETVALUE(iCurIdx, iNum);

}

return iRet;

}

int main()

{

int auiInsertNum[7] = {4, 2, 4, 3, 6, 5, 7};

int i;

BST_ARRAY_INIT();

for (i = 0; i < 7; i++)

{

BST_Insert(auiInsertNum[i]);

}

BST_ARRAY_DISPLAY();

}

运行结果

CurIdx :1 Value :4

CurIdx :2 Value :2

CurIdx :1 Value :4 The value already exist.

CurIdx :1 Value :4

CurIdx :5 Value :3

CurIdx :3 Value :6

CurIdx :6 Value :5

CurIdx :7 Value :7

0 4 2 6 0 3 5 7 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0

二叉数遍历方法“(均以根节点为基准)

0818b9ca8b590ca3270a3433284dd417.png

a)先序遍历:

先访问根节点,再遍历左子树,后遍历右子树;

先序遍历顺序为:ABDECF

b)中序遍历

先遍历左子树,中间访问根节点,后遍历右子树;

中序遍历顺序为:DBEAFC

c)后序遍历

先遍历左子树,再遍历右子树,后访问根节点

后序遍历顺序:DEBFCA

2、完全二叉树

除最后一层外,其余层上的节点数均达到最大值,且最后一层只缺少右边的若干节点。如堆就是完全二叉树。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值