C语言实现数据结构之二叉树

[复制链接]
发表于 2024-11-18 04:22:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
二叉树

一. 树概念及结构

1. 树的概念

树是一种非线性的数据结构,它是由n(n>=0)个有限结点构成一个具有条理关系的集合。把它叫做树是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。


  • 有一个特别的结点,称为根结点,根结点没有前驱结点
  • 除根结点外,其余结点被分成M(M>0)个互不相交的集合                                                   T                               1                                      、                                       T                               2                                      、                            …                            …                            、                                       T                               m                                            T_1、T_2、……、T_m                     T1​、T2​、……、Tm​,此中每一个集合                                                   T                               i                                      (                            1                            <                            =                            i                            <                            =                            m                            )                                  T_i(1<= i<=m)                     Ti​(1<=i<=m)又是一棵结构与树类似的子树。每棵子树的根结点有且只有一个前驱,可以有0个或多个后继
  • 因此,树是递归界说的。
注意:树形结构中,子树之间不能有交集,否则就不是树形结构

2. 树的相关概念




  • 结点的度:一个结点含有的子树的个数称为该结点的度; 如上图:A的度为6
  • 叶结点或终端结点:度为0的结点称为叶结点; 如上图:B、C、H、I…等结点为叶结点
  • 非终端结点或分支结点:度不为0的结点; 如上图:D、E、F、G…等结点为分支结点
  • 双亲结点或父结点:若一个结点含有子结点,则这个结点称为其子结点的父结点; 如上图:A是B的父结点
  • 孩子结点或子结点:一个结点含有的子树的根结点称为该结点的子结点; 如上图:B是A的孩子结点
  • 兄弟结点:具有雷同父结点的结点互称为兄弟结点; 如上图:B、C是兄弟结点
  • 树的度:一棵树中,最大的结点的度称为树的度; 如上图:树的度为6
  • 结点的条理:从根开始界提及,根为第1层,根的子结点为第2层,以此类推;
  • 树的高度或深度:树中结点的最大条理; 如上图:树的高度为4
  • 堂兄弟结点:双亲在同一层的结点互为堂兄弟;如上图:H、I互为兄弟结点
  • 结点的祖先:从根到该结点所经分支上的所有结点;如上图:A是所有结点的祖先
  • 子孙:以某结点为根的子树中任一结点都称为该结点的子孙。如上图:所有结点都是A的子孙
  • 森林:由m(m>0)棵互不相交的树的集合称为森林;
3. 树的表现

树结构相对线性表就比力复杂了,要存储表现起来就比力麻烦了,既要生存值域,也要生存结点和结点之间的关系,现实中树有很多种表现方式如:双亲表现法,孩子表现法、孩子双亲表现法以及孩子兄弟表现法等。我们这里就简朴的相识此中最常用的孩子兄弟表现法。
  1. typedef int DataType;
  2. struct Node
  3. {
  4.         struct Node* firstChild1; // 第一个孩子结点
  5.         struct Node* pNextBrother; // 指向其下一个兄弟结点
  6.         DataType data; // 结点中的数据域
  7. };
复制代码

4. 树在现实中的运用(表现文件系统的目录树结构)


二. 二叉树概念及结构

1. 概念

一棵二叉树是结点的一个有限集合,该集合:

  • 或者为空
  • 由一个根结点加上两棵别称为左子树和右子树的二叉树构成

从上图可以看出:

  • 二叉树不存在度大于2的结点
  • 二叉树的子树有左右之分,次序不能颠倒,因此二叉树是有序树
    注意:对于任意的二叉树都是由以下几种环境复合而成的:

2. 特别的二叉树


  • 满二叉树:一个二叉树,如果每一个层的结点数都到达最大值,则这个二叉树就是满二叉树。也就是说,如果一个二叉树的层数为K,且结点总数是                                                   2                               k                                      −                            1                                  2^k -1                     2k−1 ,则它就是满二叉树。
  • 完全二叉树:完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对于深度为K的,有n个结点的二叉树,当且仅当其每一个结点都与深度为K的满二叉树中编号从1至n的结点逐一对应时称之为完全二叉树。 要注意的是满二叉树是一种特别的完全二叉树。

3. 二叉树的性子


  • 若规定根结点的层数为1,则一棵非空二叉树的第                                        i                                  i                     i层上最多有                                                   2                                           (                                  i                                  −                                  1                                  )                                                       2^{(i-1)}                     2(i−1)个结点.
  • 若规定根结点的层数为1,则深度为                                        h                                  h                     h的二叉树的最大结点数是                                                   2                               h                                      −                            1                                  2^h-1                     2h−1.
  • 对任何一棵二叉树, 如果度为0其叶结点个数为                                                   n                               0                                            n_0                     n0​, 度为2的分支结点个数为                                                   n                               2                                            n_2                     n2​,则有                                                   n                               0                                      =                                       n                               2                                      +                            1                                  n_0=n_2+1                     n0​=n2​+1
  1. /*
  2. * 假设二叉树有N个结点
  3. * 从总结点数角度考虑:N = n0 + n1 + n2 ①
  4. *
  5. * 从边的角度考虑,N个结点的任意二叉树,总共有N-1条边
  6. * 因为二叉树中每个结点都有双亲,根结点没有双亲,每个节点向上与其双亲之间存在一条边
  7. * 因此N个结点的二叉树总共有N-1条边
  8. * 因为度为0的结点没有孩子,故度为0的结点不产生边; 度为1的结点只有一个孩子,故每个度
  9. * 为1的结点产生一条边; 度为2的结点有2个孩子,故每个度为2的结点产生两条边,所以总边
  10. * 为:n1+2*n2
  11. * 故从边的角度考虑:N-1 = n1 + 2*n2 ②
  12. * 结合① 和 ②得:n0 + n1 + n2 = n1 + 2*n2 - 1
  13. * 即:n0 = n2 + 1
  14. */
复制代码

  • 若规定根结点的层数为1,具有n个结点的满二叉树的深度,                                        h                            =                            l                            o                                       g                               2                                      (                            n                            +                            1                            )                                  h= log_2(n + 1)                     h=log2​(n+1). (ps:                                         h                            =                            l                            o                                       g                               2                                      (                            n                            +                            1                            )                                  h= log_2(n + 1)                     h=log2​(n+1)是log以2为底,n+1为对数)
  • 对于具有n个结点的完全二叉树,如果按照从上至下从左至右的数组顺序对所有结点从0开始编号,则对于序号为i的结点有:
   

  • 若i>0,i位置结点的双亲序号:(i-1)/2;i=0,i为根结点编号,无双亲结点
  • 若2i+1<n,左孩子序号:2i+1,2i+1>=n否则无左孩子
  • 若2i+2<n,右孩子序号:2i+2,2i+2>=n否则无右孩子
   

  • 某二叉树共有 399 个结点,此中有 199 个度为 2 的结点,则该二叉树中的叶子结点数为( )
    A 不存在如许的二叉树
    B 200
    C 198
    D 199
  • 下列数据结构中,不得当采用顺序存储结构的是( )
    A 非完全二叉树
    B 堆
    C 队列
    D 栈
  • 在具有 2n 个结点的完全二叉树中,叶子结点个数为( )
    A n
    B n+1
    C n-1
    D n/2
  • 一棵完全二叉树的结点数位为531个,那么这棵树的高度为( )
    A 11
    B 10
    C 8
    D 12
  • 一个具有767个结点的完全二叉树,其叶子结点个数为()
    A 383
    B 384
    C 385
    D 386
    答案:
1.B
2.A
3.A
4.B
5.B
  4. 二叉树的存储结构

二叉树一般可以使用两种结构存储,一种顺序结构,一种链式结构。

  • 顺序存储
    顺序结构存储就是使用数组来存储,一般使用数组只得当表现完全二叉树,因为不是完全二叉树会有空间的浪费。而现实中使用中只有堆才会使用数组来存储,关于堆我们后面的章节会专门讲授。二叉树顺序存储在物理上是一个数组,在逻辑上是一颗二叉树。

  • 链式存储
    二叉树的链式存储结构是指,用链表来表现一棵二叉树,即用链来指示元素的逻辑关系。 通常的方法是链表中每个结点由三个域构成,数据域和左右指针域,左右指针分别用来给出该结点左孩子和右孩子地点的链结点的存储地址 。链式结构又分为二叉链和三叉链,当前我们学习中一般都是二叉链,后面学到高阶数据结构如红黑树等会用到三叉链。

  1. typedef int BTDataType;
  2. // 二叉链
  3. struct BinaryTreeNode
  4. {
  5.         struct BinTreeNode* left; // 指向当前结点左孩子
  6.         struct BinTreeNode* right; // 指向当前结点右孩子
  7.         BTDataType data; // 当前结点值域
  8. }
  9. // 三叉链
  10. struct BinaryTreeNode
  11. {
  12.         struct BinTreeNode* parent; // 指向当前结点的双亲
  13.         struct BinTreeNode* left; // 指向当前结点左孩子
  14.         struct BinTreeNode* right; // 指向当前结点右孩子
  15.         BTDataType data; // 当前结点值域
  16. };
复制代码
三.二叉树链式结构的实现

1. 前置说明

在学习二叉树的基本操纵前,需先要创建一棵二叉树,然后才能学习其相关的基本操纵。由于现在大家对二叉树结构把握还不够深入,为了降低大家学习成本,此处手动快速创建一棵简朴的二叉树,快速进入二叉树操纵学习,等二叉树结构相识的差不多时,我们反过头再来研究二叉树真正的创建方式。
  1. typedef int BTDataType;
  2. typedef struct BinaryTreeNode
  3. {
  4.         BTDataType _data;
  5.         struct BinaryTreeNode* _left;
  6.         struct BinaryTreeNode* _right;
  7. }BTNode;
  8. BTNode* CreatBinaryTree()
  9. {
  10.         BTNode* node1 = BuyNode(1);
  11.         BTNode* node2 = BuyNode(2);
  12.         BTNode* node3 = BuyNode(3);
  13.         BTNode* node4 = BuyNode(4);
  14.         BTNode* node5 = BuyNode(5);
  15.         BTNode* node6 = BuyNode(6);
  16.         node1->_left = node2;
  17.         node1->_right = node4;
  18.         node2->_left = node3;
  19.         node4->_left = node5;
  20.         node4->_right = node6;
  21.         return node1;
  22. }
复制代码
注意:上述代码并不是创建二叉树的方式,真正创建二叉树方式后序详解重点讲授。
再看二叉树基本操纵前,再回顾下二叉树的概念,二叉树是:
   

  • 空树
  • 非空:根结点,根结点的左子树、根结点的右子树构成的。
  从概念中可以看出,二叉树界说是递归式的,因此后序基本操纵中基本都是按照该概念实现的。
2. 二叉树的遍历

2.1 前序、中序以及后序遍历

学习二叉树结构,最简朴的方式就是遍历。所谓二叉树遍历(Traversal)是按照某种特定的规则,依次对二叉树中的结点进行相应的操纵,而且每个结点只操纵一次。访问结点所做的操纵依靠于具体的应用问题。 遍历是二叉树上最重要的运算之一,也是二叉树上进行其它运算的基础。
按照规则,二叉树的遍历有:前序/中序/后序的递归结构遍历:

  • 前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点的操纵发生在遍历其左右子树之前。
  • 中序遍历(Inorder Traversal)——访问根结点的操纵发生在遍历其左右子树之中(间)。
  • 后序遍历(Postorder Traversal)——访问根结点的操纵发生在遍历其左右子树之后。
    由于被访问的结点必是某子树的根,以是N(Node)、L(Left subtree)和R(Right subtree)又可解释为根、根的左子树和根的右子树。NLR、LNR和LRN分别又称为先根遍历、中根遍历和后根遍历。
  1. // 二叉树前序遍历
  2. void PreOrder(BTNode* root);
  3. // 二叉树中序遍历
  4. void InOrder(BTNode* root);
  5. // 二叉树后序遍历
  6. void PostOrder(BTNode* root);
复制代码
下面重要分析前序递归遍历,中序与后序图解类似,同砚们可自己动手绘制。
前序遍历递归图解:

前序遍历结果:1 2 3 4 5 6
中序遍历结果:3 2 1 5 4 6
后序遍历结果:3 2 5 6 4 1
2.1.1 前序遍历 BinaryTreePrevOrder

  1. void BinaryTreePrevOrder(BTNode* root)//前序遍历
  2. {
  3.         if (root == NULL)
  4.         {
  5.                 printf("NULL ");
  6.                 return;
  7.         }
  8.         printf("%d ", root->data);
  9.         BinaryTreePrevOrder(root->left);
  10.         BinaryTreePrevOrder(root->right);
  11. }
复制代码
2.1.2 中序遍历 BinaryTreeInOrder

  1. void BinaryTreeInOrder(BTNode* root)//中序遍历
  2. {
  3.         if (root == NULL)
  4.         {
  5.                 printf("NULL ");
  6.                 return;
  7.         }
  8.         BinaryTreeInOrder(root->left);
  9.         printf("%d ", root->data);
  10.         BinaryTreeInOrder(root->right);
  11. }
复制代码
2.1.3 后序遍历 BinaryTreePostOrder

  1. void BinaryTreePostOrder(BTNode* root)//后序遍历
  2. {
  3.         if (root == NULL)
  4.         {
  5.                 printf("NULL ");
  6.                 return;
  7.         }
  8.         BinaryTreePostOrder(root->left);
  9.         BinaryTreePostOrder(root->right);
  10.         printf("%d ", root->data);
  11. }
复制代码
2.2 层序遍历

层序遍历:除了先序遍历、中序遍历、后序遍历外,还可以对二叉树进行层序遍历。设二叉树的根结点地点层数为1,层序遍历就是从地点二叉树的根结点出发,起首访问第一层的树根结点,然后从左到右访问第2层上的结点,接着是第三层的结点,以此类推,自上而下,自左至右逐层访问树的结点的过程就是层序遍历。

  1. // 层序遍历
  2. void LevelOrder(BTNode* root);
复制代码
2.2.1 层序遍历 BinaryTreeLevelOrder

  1. typedef struct BinaryTreeNode* QDataType;
复制代码
  1. #include "Queue.h"
  2. void BinaryTreeLevelOrder(BTNode* root)
  3. {
  4.         Queue Q;
  5.         QueueInit(&Q);
  6.         if (root)
  7.                 QueuePush(&Q, root);
  8.        
  9.         while (!QueueEmpty(&Q))
  10.         {
  11.                 BTNode* front = QueueFront(&Q);
  12.                 QueuePop(&Q);
  13.                 printf("%d ", front->data);
  14.                 if (front->left)
  15.                         QueuePush(&Q, front->left);
  16.                 if (front->right)
  17.                         QueuePush(&Q, front->right);
  18.         }
  19. }
复制代码
练习:请写出下面的前序/中序/后序/层序遍历

   选择题
  

  • 某完全二叉树按条理输出(同一层从左到右)的序列为 ABCDEFGH 。该完全二叉树的前序序列为( )
    A ABDHECFG
    B ABCDEFGH
    C HDBEAFCG
    D HDEBFGCA
  • 二叉树的先序遍历和中序遍历如下:先序遍历:EFHIGJK;中序遍历:HFIEJKG.则二叉树根结点为()
    A E
    B F
    C G
    D H
  • 设一课二叉树的中序遍历序列:badce,后序遍历序列:bdeca,则二叉树前序遍历序列为____。
    A adbce
    B decab
    C debac
    D abcde
  • 某二叉树的后序遍历序列与中序遍历序列雷同,均为 ABCDEF ,则按条理输出(同一层从左到右)的序列为
    A FEDCBA
    B CBAFED
    C DEFCBA
    D ABCDEF
    选择题答案
  

  • A
  • A
  • D
  • A
  3. 结点个数以及高度等

  1. // 二叉树结点个数
  2. int BinaryTreeSize(BTNode* root);
  3. // 二叉树叶子结点个数
  4. int BinaryTreeLeafSize(BTNode* root);
  5. // 二叉树第k层结点个数
  6. int BinaryTreeLevelKSize(BTNode* root, int k);
  7. // 二叉树查找值为x的结点
  8. BTNode* BinaryTreeFind(BTNode* root, BTDataType x);
复制代码
3.1 二叉树结点个数 BinaryTreeSize

  1. int BinaryTreeSize(BTNode* root)//节点个数
  2. {
  3.         return root == NULL ? 0 : \
  4.                 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
  5. }
复制代码
3.2 二叉树叶子结点个数 BinaryTreeLeafSize

  1. int BinaryTreeLeafSize(BTNode* root)//叶子节点个数
  2. {
  3.         if (root == NULL)
  4.                 return 0;
  5.         if (root->left == NULL && root->right == NULL)
  6.                 return 1;
  7.         return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
  8. }
复制代码
3.3 二叉树第k层结点个数 BinaryTreeLevelKSize

  1. int BinaryTreeLevelKSize(BTNode* root, int k)
  2. {
  3.         if (root == NULL)
  4.                 return 0;
  5.         //if (k == 1 && root != NULL)
  6.         if (k == 1)
  7.                 return 1;
  8.         //if (k > 1 && root != NULL)
  9.         return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
  10. }
复制代码
3.4 二叉树查找值为x的结点 BinaryTreeFind

  1. BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
  2. {
  3.         if(root == NULL)
  4.                 return NULL;
  5.         if (root->data == x)
  6.                 return root;
  7.         BTNode* left = BinaryTreeFind(root->left, x);
  8.         if (left)
  9.                 return left;
  10.         BTNode* right = BinaryTreeFind(root->right, x);
  11.         if (right)
  12.                 return right;
  13.         return NULL;
  14. }
复制代码
4. 二叉树基础oj练习

4.1 单值二叉树

单值二叉树。Oj链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. bool isUnivalTree(struct TreeNode* root)
  10. {
  11.     if(root == NULL)
  12.         return true;
  13.     if(root->left && root->left->val != root->val)
  14.         return false;
  15.    
  16.     if(root->right && root->right->val != root->val)
  17.         return false;
  18.     return isUnivalTree(root->left) && isUnivalTree(root->right);
  19. }
复制代码
4.2 检查两颗树是否雷同

检查两颗树是否雷同。OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. bool isSameTree(struct TreeNode* p, struct TreeNode* q)
  10. {
  11.     if(p == NULL && q == NULL)//都为空
  12.         return true;
  13.     if(p == NULL || q == NULL)//其中一个不为空
  14.         return false;
  15.     if(p->val != q->val)
  16.         return false;
  17.     return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
  18. }
复制代码
4.3 对称二叉树

对称二叉树。OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. bool _isSymmetric(struct TreeNode* p, struct TreeNode* q)
  10. {
  11.     if(p == NULL && q == NULL)
  12.         return true;
  13.     if(p == NULL || q == NULL)
  14.         return false;
  15.     if(p->val != q->val)
  16.         return false;
  17.     return _isSymmetric(p->left, q->right) && _isSymmetric(p->right, q->left);
  18. }
  19. bool isSymmetric(struct TreeNode* root)
  20. {
  21.     return _isSymmetric(root->left, root->right);
  22. }
复制代码
4.4 二叉树的前序遍历

二叉树的前序遍历。 OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. /**
  10. * Note: The returned array must be malloced, assume caller calls free().
  11. */
  12. int BinaryTreeSize(struct TreeNode* root)//节点个数
  13. {
  14.         return root == NULL ? 0 : 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
  15. }
  16. void BinaryTreePrevOrder(struct TreeNode* root, int* arr, int* num)//前序遍历
  17. {
  18.         if (root == NULL)
  19.                 return;
  20.         arr[(*num)++] = root->val;
  21.         BinaryTreePrevOrder(root->left, arr, num);
  22.         BinaryTreePrevOrder(root->right, arr, num);
  23. }
  24. int* preorderTraversal(struct TreeNode* root, int* returnSize)
  25. {
  26.     *returnSize = BinaryTreeSize(root);
  27.     int* arr = malloc(sizeof(int) * (*returnSize));
  28.     int num = 0;
  29.     BinaryTreePrevOrder(root, arr, &num);
  30.     return arr;
  31. }
复制代码
4.5 二叉树中序遍历

二叉树中序遍历 。OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. /**
  10. * Note: The returned array must be malloced, assume caller calls free().
  11. */
  12. int BinaryTreeSize(struct TreeNode* root)//节点个数
  13. {
  14.         return root == NULL ? 0 : 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
  15. }
  16. void BinaryTreeInOrder(struct TreeNode* root, int* arr, int* num)//前序遍历
  17. {
  18.         if (root == NULL)
  19.                 return;
  20.        
  21.         BinaryTreeInOrder(root->left, arr, num);
  22.     arr[(*num)++] = root->val;
  23.         BinaryTreeInOrder(root->right, arr, num);
  24. }
  25. int* inorderTraversal(struct TreeNode* root, int* returnSize)
  26. {
  27.     *returnSize = BinaryTreeSize(root);
  28.     int* arr = malloc(sizeof(int) * (*returnSize));
  29.     int num = 0;
  30.     BinaryTreeInOrder(root, arr, &num);
  31.     return arr;   
  32. }
复制代码
4.6 二叉树的后序遍历

二叉树的后序遍历 。OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. /**
  10. * Note: The returned array must be malloced, assume caller calls free().
  11. */
  12.   int BinaryTreeSize(struct TreeNode* root)//节点个数
  13. {
  14.         return root == NULL ? 0 : 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
  15. }
  16. void BinaryTreePostOrder(struct TreeNode* root, int* arr, int* num)//前序遍历
  17. {
  18.         if (root == NULL)
  19.                 return;
  20.        
  21.         BinaryTreePostOrder(root->left, arr, num);
  22.         BinaryTreePostOrder(root->right, arr, num);
  23.     arr[(*num)++] = root->val;
  24. }
  25. int* postorderTraversal(struct TreeNode* root, int* returnSize)
  26. {
  27.     *returnSize = BinaryTreeSize(root);
  28.     int* arr = malloc(sizeof(int) * (*returnSize));
  29.     int num = 0;
  30.     BinaryTreePostOrder(root, arr, &num);
  31.     return arr;   
  32. }
复制代码
4.7 另一颗树的子树

另一颗树的子树。OJ链接
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. *     int val;
  5. *     struct TreeNode *left;
  6. *     struct TreeNode *right;
  7. * };
  8. */
  9. bool isSameTree(struct TreeNode* p, struct TreeNode* q)
  10. {
  11.     if(p == NULL && q == NULL)//都为空
  12.         return true;
  13.     if(p == NULL || q == NULL)//其中一个不为空
  14.         return false;
  15.     if(p->val != q->val)
  16.         return false;
  17.     return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
  18. }
  19. bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){    if(root == NULL)        return false;    if(root->val == subRoot->val && isSameTree(root, subRoot))    return true;    return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);}
复制代码
5 二叉树的创建和销毁

  1. // 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
  2. BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi);
  3. // 二叉树销毁
  4. void BinaryTreeDestory(BTNode** root);
  5. // 判断二叉树是否是完全二叉树
  6. int BinaryTreeComplete(BTNode* root);
复制代码
1.二叉树的构建及遍历

二叉树的构建及遍历OJ链接
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef char BTDataType;
  4. typedef struct BinaryTreeNode
  5. {
  6.         BTDataType data;
  7.         struct BinaryTreeNode* left;
  8.         struct BinaryTreeNode* right;
  9. }BTNode;
  10. BTNode* CreatTree(char* arr, int* num)
  11. {
  12.     if(arr[*num] == '#')
  13.     {
  14.         (*num)++;
  15.         return NULL;
  16.     }
  17.     BTNode* root = malloc(sizeof(BTNode));
  18.     if(root == NULL)
  19.     {
  20.         perror("malloc failed");
  21.         return NULL;
  22.     }
  23.     root->data = arr[(*num)++];
  24.     root->left = CreatTree(arr, num);
  25.     root->right = CreatTree(arr, num);
  26.     return root;
  27. }
  28. void BinaryTreeInOrder(BTNode* root)//中序遍历
  29. {
  30.         if (root == NULL)
  31.         {
  32.                 return;
  33.         }
  34.         BinaryTreeInOrder(root->left);
  35.         printf("%c ", root->data);
  36.         BinaryTreeInOrder(root->right);
  37. }
  38. int main()
  39. {
  40.     char arr[100] = { 0 };
  41.     scanf("%s", arr);
  42.     int num = 0;
  43.     BTNode* root = CreatTree(arr, &num);
  44.     BinaryTreeInOrder(root);
  45.     return 0;
  46. }
复制代码
2. 前序遍历构建二叉树 BinaryTreeCreate

通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
  1. BTNode* BinaryTreeCreate(BTDataType* arr, int num, int* pi)
  2. {
  3.         if (*pi >= num)
  4.         {
  5.                 return NULL;
  6.         }
  7.         if (arr[*pi] == '#')
  8.         {
  9.                 (*pi)++;
  10.                 return NULL;
  11.         }
  12.         BTNode* root = malloc(sizeof(BTNode));
  13.         if (root == NULL)
  14.         {
  15.                 perror("malloc failed");
  16.                 return NULL;
  17.         }
  18.         root->data = arr[(*pi)++];
  19.         root->left = BinaryTreeCreate(arr, num, pi);
  20.         root->right = BinaryTreeCreate(arr, num, pi);
  21.         return root;
  22. }
复制代码
3. 二叉树销毁 BinaryTreeDestory

  1. void BinaryTreeDestory(BTNode** root)
  2. {
  3.         if (*root == NULL)
  4.                 return;
  5.         BinaryTreeDestory(&((*root)->left));
  6.         BinaryTreeDestory(&((*root)->right));
  7.         free(*root);
  8.         *root = NULL;
  9. }
复制代码
4. 判断二叉树是否是完全二叉树 BinaryTreeComplete

  1. typedef struct BinaryTreeNode* QDataType;
复制代码
  1. #include "Queue.h"
  2. bool BinaryTreeComplete(BTNode* root)
  3. {
  4.         Queue Q;
  5.         QueueInit(&Q);
  6.         if (root)
  7.                 QueuePush(&Q, root);
  8.         while (!QueueEmpty(&Q))
  9.         {
  10.                 BTNode* front = QueueFront(&Q);
  11.                 QueuePop(&Q);
  12.                 //遇到第一个空,开始判断
  13.                 if (front == NULL)
  14.                 {
  15.                         break;
  16.                 }
  17.                 QueuePush(&Q, front->left);
  18.                 QueuePush(&Q, front->right);
  19.         }
  20.         while (!QueueEmpty(&Q))
  21.         {
  22.                 BTNode* front = QueueFront(&Q);
  23.                 QueuePop(&Q);
  24.                 //如果有非空,就不是完全二叉树
  25.                 if (front)
  26.                 {
  27.                         QueueDestroy(&Q);
  28.                         return false;
  29.                 }
  30.         }
  31.         QueueDestroy(&Q);
  32.         return true;
  33. }
复制代码
四. 参考代码

BinaryTree.h

  1. #pragma once
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. typedef int BTDataType;
  6. typedef struct BinaryTreeNode
  7. {
  8.         BTDataType data;
  9.         struct BinaryTreeNode* left;
  10.         struct BinaryTreeNode* right;
  11. }BTNode;
  12. // 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
  13. BTNode* BinaryTreeCreate(BTDataType* arr, int num, int* pi);
  14. // 二叉树销毁
  15. void BinaryTreeDestory(BTNode** root);
  16. // 二叉树节点个数
  17. int BinaryTreeSize(BTNode* root);
  18. // 二叉树叶子节点个数
  19. int BinaryTreeLeafSize(BTNode* root);
  20. // 二叉树第k层节点个数
  21. int BinaryTreeLevelKSize(BTNode* root, int k);
  22. // 二叉树查找值为x的节点
  23. BTNode* BinaryTreeFind(BTNode* root, BTDataType x);
  24. // 二叉树前序遍历
  25. void BinaryTreePrevOrder(BTNode* root);
  26. // 二叉树中序遍历
  27. void BinaryTreeInOrder(BTNode* root);
  28. // 二叉树后序遍历
  29. void BinaryTreePostOrder(BTNode* root);
  30. // 层序遍历
  31. void BinaryTreeLevelOrder(BTNode* root);
  32. // 判断二叉树是否是完全二叉树
  33. bool BinaryTreeComplete(BTNode* root);
复制代码
BinaryTree.c

  1. #include "BinaryTree.h"BTNode* BinaryTreeCreate(BTDataType* arr, int num, int* pi)
  2. {
  3.         if (*pi >= num)
  4.         {
  5.                 return NULL;
  6.         }
  7.         if (arr[*pi] == '#')
  8.         {
  9.                 (*pi)++;
  10.                 return NULL;
  11.         }
  12.         BTNode* root = malloc(sizeof(BTNode));
  13.         if (root == NULL)
  14.         {
  15.                 perror("malloc failed");
  16.                 return NULL;
  17.         }
  18.         root->data = arr[(*pi)++];
  19.         root->left = BinaryTreeCreate(arr, num, pi);
  20.         root->right = BinaryTreeCreate(arr, num, pi);
  21.         return root;
  22. }
  23. void BinaryTreeDestory(BTNode** root)
  24. {
  25.         if (*root == NULL)
  26.                 return;
  27.         BinaryTreeDestory(&((*root)->left));
  28.         BinaryTreeDestory(&((*root)->right));
  29.         free(*root);
  30.         *root = NULL;
  31. }
  32. int BinaryTreeSize(BTNode* root)//节点个数
  33. {
  34.         return root == NULL ? 0 : \
  35.                 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
  36. }
  37. int BinaryTreeLeafSize(BTNode* root)//叶子节点个数
  38. {
  39.         if (root == NULL)
  40.                 return 0;
  41.         if (root->left == NULL && root->right == NULL)
  42.                 return 1;
  43.         return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
  44. }
  45. int BinaryTreeLevelKSize(BTNode* root, int k)
  46. {
  47.         if (root == NULL)
  48.                 return 0;
  49.         //if (k == 1 && root != NULL)
  50.         if (k == 1)
  51.                 return 1;
  52.         //if (k > 1 && root != NULL)
  53.         return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
  54. }
  55. BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
  56. {
  57.         if(root == NULL)
  58.                 return NULL;
  59.         if (root->data == x)
  60.                 return root;
  61.         BTNode* left = BinaryTreeFind(root->left, x);
  62.         if (left)
  63.                 return left;
  64.         BTNode* right = BinaryTreeFind(root->right, x);
  65.         if (right)
  66.                 return right;
  67.         return NULL;
  68. }
  69. void BinaryTreePrevOrder(BTNode* root)//前序遍历
  70. {
  71.         if (root == NULL)
  72.         {
  73.                 printf("NULL ");
  74.                 return;
  75.         }
  76.         printf("%d ", root->data);
  77.         BinaryTreePrevOrder(root->left);
  78.         BinaryTreePrevOrder(root->right);
  79. }
  80. void BinaryTreeInOrder(BTNode* root)//中序遍历
  81. {
  82.         if (root == NULL)
  83.         {
  84.                 printf("NULL ");
  85.                 return;
  86.         }
  87.         BinaryTreeInOrder(root->left);
  88.         printf("%d ", root->data);
  89.         BinaryTreeInOrder(root->right);
  90. }
  91. void BinaryTreePostOrder(BTNode* root)//后序遍历
  92. {
  93.         if (root == NULL)
  94.         {
  95.                 printf("NULL ");
  96.                 return;
  97.         }
  98.         BinaryTreePostOrder(root->left);
  99.         BinaryTreePostOrder(root->right);
  100.         printf("%d ", root->data);
  101. }
  102. #include "Queue.h"
  103. void BinaryTreeLevelOrder(BTNode* root)
  104. {
  105.         Queue Q;
  106.         QueueInit(&Q);
  107.         if (root)
  108.                 QueuePush(&Q, root);
  109.        
  110.         while (!QueueEmpty(&Q))
  111.         {
  112.                 BTNode* front = QueueFront(&Q);
  113.                 QueuePop(&Q);
  114.                 printf("%d ", front->data);
  115.                 if (front->left)
  116.                         QueuePush(&Q, front->left);
  117.                 if (front->right)
  118.                         QueuePush(&Q, front->right);
  119.         }
  120. }
  121. bool BinaryTreeComplete(BTNode* root){        Queue Q;        QueueInit(&Q);        if (root)                QueuePush(&Q, root);        while (!QueueEmpty(&Q))        {                BTNode* front = QueueFront(&Q);                QueuePop(&Q);                //遇到第一个空,开始判断                if (front == NULL)                {                        break;                }                QueuePush(&Q, front->left);                QueuePush(&Q, front->right);        }        while (!QueueEmpty(&Q))        {                BTNode* front = QueueFront(&Q);                QueuePop(&Q);                //如果有非空,就不是完全二叉树                if (front)                {                        QueueDestroy(&Q);                        return false;                }        }        QueueDestroy(&Q);        return true;}
复制代码
Queue.h

  1. #pragma once#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <stdbool.h>typedef struct BinaryTreeNode* QDataType;
  2. typedef struct QueueNode{        struct QueueNode* next;        QDataType val;}QNode;typedef struct Queue{        QNode* phead;         QNode* ptail;        int size;}Queue;队尾插入//void QueuePush(QNode** pphead, QNode** pptail, QDataType x);//队头删除//void QueuePop(QNode** pphead, QNode** pptail);//初始化void QueueInit(Queue* pq);//队尾插入void QueuePush(Queue* pq, QDataType x);//队头删除void QueuePop(Queue* pq);//取队头数据QDataType QueueFront(Queue* pq);//取队尾数据QDataType QueueBack(Queue* pq);//队列元素个数int QueueSize(Queue* pq);//判空_Bool QueueEmpty(Queue* pq);//队列的销毁void QueueDestroy(Queue* pq);
复制代码
Queue.c

  1. #include "Queue.h"
  2. void QueueInit(Queue* pq)
  3. {
  4.         assert(pq);
  5.         pq->phead = NULL;
  6.         pq->ptail = NULL;
  7.         pq->size = 0;
  8. }
  9. void QueuePush(Queue* pq, QDataType x)
  10. {
  11.         QNode* newnode = (QNode*)malloc(sizeof(QNode));
  12.         if (newnode == NULL)
  13.         {
  14.                 perror("malloc failed");
  15.                 exit(1);
  16.         }
  17.         newnode->next = NULL;
  18.         newnode->val = x;
  19.         if (pq->ptail == NULL)
  20.         {
  21.                 pq->phead = newnode;
  22.                 pq->ptail = newnode;
  23.         }
  24.         else
  25.         {
  26.                 pq->ptail->next = newnode;
  27.                 pq->ptail = newnode;
  28.         }
  29.         pq->size++;
  30. }
  31. void QueuePop(Queue* pq)
  32. {
  33.         assert(pq);
  34.         assert(pq->size);
  35.         QNode* next = pq->phead->next;
  36.         free(pq->phead);
  37.         pq->phead = next;
  38.         if (pq->phead == NULL)//只有一个节点的情况
  39.         {
  40.                 pq->ptail = NULL;
  41.         }
  42.         pq->size--;
  43. }
  44. QDataType QueueFront(Queue* pq)
  45. {
  46.         assert(pq);
  47.         assert(pq->phead);
  48.         return pq->phead->val;
  49. }
  50. QDataType QueueBack(Queue* pq)
  51. {
  52.         assert(pq);
  53.         assert(pq->ptail);
  54.         return pq->ptail->val;
  55. }
  56. int QueueSize(Queue* pq)
  57. {
  58.         assert(pq);
  59.         return pq->size;
  60. }
  61. _Bool QueueEmpty(Queue* pq)
  62. {
  63.         assert(pq);
  64.         return pq->size == 0;
  65. }
  66. void QueueDestroy(Queue* pq)
  67. {
  68.         assert(pq);
  69.         QNode* pcur = pq->phead;
  70.         while (pcur)
  71.         {
  72.                 QNode* next = pcur->next;
  73.                 free(pcur);
  74.                 pcur = next;
  75.         }
  76.         pq->phead = NULL;
  77.         pq->ptail = NULL;
  78.         pq->size = 0;
  79. }
复制代码
test.c

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. //#include "vld.h"
  3. #include "BinaryTree.h"
  4. BTNode* BuyNode(BTDataType x)
  5. {
  6.         BTNode* node = (BTNode*)malloc(sizeof(BTNode));
  7.         if (node == NULL)
  8.         {
  9.                 perror("malloc failed");
  10.                 return NULL;
  11.         }
  12.         node->data = x;
  13.         node->left = NULL;
  14.         node->right = NULL;
  15.         return node;
  16. }
  17. BTNode* CreatBinaryTree()
  18. {
  19.         BTNode* node1 = BuyNode(1);
  20.         BTNode* node2 = BuyNode(2);
  21.         BTNode* node3 = BuyNode(3);
  22.         BTNode* node4 = BuyNode(4);
  23.         BTNode* node5 = BuyNode(5);
  24.         BTNode* node6 = BuyNode(6);
  25.         node1->left = node2;
  26.         node1->right = node4;
  27.         node2->left = node3;
  28.         node4->left = node5;
  29.         node4->right = node6;
  30.         return node1;
  31. }
  32. //int TreeHeight(BTNode* root)
  33. //{
  34. //        if (root == NULL)
  35. //                return 0;
  36. //
  37. //        return TreeHeight(root->left) > TreeHeight(root->right) ? \
  38. //                TreeHeight(root->left) + 1 : TreeHeight(root->right) + 1;
  39. //}
  40. //求树的高度
  41. int TreeHeight(BTNode* root)
  42. {
  43.         if (root == NULL)
  44.                 return 0;
  45.         int leftHeight = TreeHeight(root->left);
  46.         int rightHeight = TreeHeight(root->right);
  47.         return leftHeight > rightHeight ? \
  48.                 leftHeight + 1 : rightHeight + 1;
  49.         //return fmax(TreeHeight(root->left), TreeHeight(root->right));
  50. }
  51. void BTTest01()
  52. {
  53.         BTNode* root = CreatBinaryTree();
  54.         BinaryTreePrevOrder(root);
  55.         printf("\n");
  56.         BinaryTreeInOrder(root);
  57.         printf("\n");
  58.         BinaryTreePostOrder(root);
  59.         printf("\n");
  60.         printf("BinaryTreeSize:%d\n", BinaryTreeSize(root));
  61.         printf("BinaryTreeSize:%d\n", BinaryTreeSize(root));
  62.         printf("BinaryTreeLeafSize:%d\n", BinaryTreeLeafSize(root));
  63.         printf("TreeHeight:%d\n", TreeHeight(root));
  64.         printf("BinaryTreeLevelKSize(1):%d\n", BinaryTreeLevelKSize(root, 1));
  65.         printf("BinaryTreeLevelKSize(2):%d\n", BinaryTreeLevelKSize(root, 2));
  66.         printf("BinaryTreeLevelKSize(3):%d\n", BinaryTreeLevelKSize(root, 3));
  67.         printf("BinaryTreeLevelKSize(4):%d\n", BinaryTreeLevelKSize(root, 4));
  68.         printf("BinaryTreeFind(1):%d\n", BinaryTreeFind(root, 1)->data);
  69.         printf("BinaryTreeFind(2):%d\n", BinaryTreeFind(root, 2)->data);
  70.         printf("BinaryTreeFind(3):%d\n", BinaryTreeFind(root, 3)->data);
  71.         printf("BinaryTreeFind(4):%d\n", BinaryTreeFind(root, 4)->data);
  72.         printf("BinaryTreeFind(5):%d\n", BinaryTreeFind(root, 5)->data);
  73.         printf("BinaryTreeFind(6):%d\n", BinaryTreeFind(root, 6)->data);
  74.         printf("BinaryTreeFind(7):%p\n", BinaryTreeFind(root, 7));
  75. }
  76. void BTTest02()
  77. {
  78.         char arr[100] = { 0 };
  79.         scanf("%s", arr);
  80.         size_t sz = sizeof(arr) / sizeof(arr[0]);
  81.         int i = 0;
  82.         BTNode* root = BinaryTreeCreate(arr, sz, &i);
  83.         BinaryTreeInOrder(root);
  84.         printf("\n");
  85.         BinaryTreeDestory(&root);
  86.         printf("%p\n", root);
  87. }
  88. BTNode* CreatBinaryTree02()//手动创建树
  89. {
  90.         BTNode* node1 = BuyNode(1);
  91.         BTNode* node2 = BuyNode(2);
  92.         BTNode* node3 = BuyNode(3);
  93.         BTNode* node4 = BuyNode(4);
  94.         BTNode* node5 = BuyNode(5);
  95.         BTNode* node6 = BuyNode(6);
  96.         node1->left = node2;
  97.         node1->right = node4;
  98.         node2->left = node3;
  99.         node2->right = node5;
  100.         node4->left = node6;
  101.         return node1;
  102. }
  103. void BTTest03()
  104. {
  105.         BTNode* root = CreatBinaryTree02();
  106.         BinaryTreeLevelOrder(root);
  107.         printf("\n");
  108.         printf("BinaryTreeComplete:%d\n", BinaryTreeComplete(root));
  109.         BinaryTreeDestory(&root);
  110. }
  111. int main()
  112. {
  113.         BTTest03();
  114.         return 0;
  115. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表