一.树
1.定义
树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。
2.树的特点
3.树和非树
4.树的表示(左孩子右兄弟表示法)
下面是图示:
5.树的实际应用
树在Linux操作系统中有着广泛应用
这里就相当于加了一个兄弟,随机模仿者版文件多了一个孩子。
二.二叉树
1.满二叉树和完全二叉树
*满二叉树:前n-1个节点,每个节点都满
满二叉树的节点个数:
2^0+2^1+......+2^(n-1)=2^n-1
*完全二叉树:前n-1都是满的,第n层从左到右连着。
高度为h的完全二叉树节点个数的范围[2^(h-1),2^h-1]
2.二叉树相关习题
对任何一棵二叉树,N0=N2+1保持不变;对于完全二叉树,N1个数非1即0。
3.二叉树的表示
很明显,不适合用数组存储表示,否则除非是完全二叉树,要不然会浪费很多空间,所以要用链式结构。
三.二叉搜索树
1.BTree.h
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int BTDataType;
typedef struct BinaryTreeNode //对应二叉树的一个节点
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
BTNode* BuyNode(BTDataType x);//开辟一个节点
BTNode* CreateTree();//建立树
void preorder(BTNode* root);//前序二叉树
void inorder(BTNode* root);//中序二叉树
void posorder(BTNode* root);//后序二叉树
int TreeSize(BTNode* root);//树中节点个数
int TreeHeight(BTNode* root);//树高
int TreeKLevel(BTNode* root, int k);//第k层节点个数
BTNode* TreeFind(BTNode* root, BTDataType x);//查找
2.BTree.c
(1).开辟节点
BTNode* BuyNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
if (node == NULL)
{
perror("malloc fail");
return NULL;
}
node->data = x;
node->left = NULL;
node->right = NULL;
}
(2).创建一个树
BTNode* CreateTree()
{
BTNode* node1 = BuyNode(1);//错误写法BTNode* BuyNode(1)
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
BTNode* node7 = BuyNode(7);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
node3->right = node7;
return node1;
}
(3).前序,中序,后序二叉树
模版:遇到谁,能不能访问,应该先访问谁。
void preorder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return NULL;
}
printf("%d ", root->data);
perorder(root->left);
perorder(root->right);
}
void inorder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return NULL;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void posorder(BTNode* root)
{
if (root == NULL)
{
printf("NULL ");
return NULL;
}
posorder(root->left);
posorder(root->right);
printf("%d ", root->data);
}
(4).树中节点个数
对于二叉树的数据统计,最核心的一个思想就是递归。
int TreeSize(BTNode* root)
{
return root == NULL ? 0 :
TreeSize(root->left) +
TreeSize(root->right) +
1;
}
(5).树高
int TreeHeight(BTNode* root)
{
if (root = NULL)
return NULL;
int leftHeight = TreeHeight(root->left);
int rightHeight = TreeHeight(root->right);
return leftHeight >= rightHeight ?
leftHeight + 1 :
rightHeight + 1;
}
(6).第k层的元素个数
int TreeKLevel(BTNode* root,int k)
{
assert(k >= 0);
if (root == NULL)
return 0;
if (k == 1)//k==1就表示该节点为一个独立节点,就可以计入数据
return 1;
return TreeKLevel(root->left, k - 1)
+ TreeKLevel(root->right, k - 1);
}
(7).二叉树查找
BTNode* TreeFind(BTNode* root, BTDataType x)
{
if (root == NULL)
return NULL;
if (root->data == x)
return root;
BTNode* lret = TreeFind(root->left, x);
if (lret)
return lret;
/*BTNode* rret = TreeFind(root->right, x);
if (rret)
return rret;
return NULL;*/
return TreeFind(root->right, x);
}