• 二叉树及其相关题目相关的功能的实现


           前言:前面我们简单提及了二叉树的相关初级知识和顺序实现二叉树的相关操作详解,并且由完全二叉树延伸到了堆的相关知识,具体详见二叉树初阶和堆的详解,今天,我们展开二叉树的相关 的链式实现操作和经常考察的二叉树的相关问题,争取一次搞定二叉树的基础问题。

     

    目录

    1.二叉树的链式实现

    1.1二叉树的三种遍历方式

    1.2 二叉树创建的两种方式

     1.2.1 已知先序(后序)+中序遍历序列

              递归建树原理解释

              代码实现:

    1.2.2 根据带空节点的任意一个遍历序列数组来建树

    1.3 二叉树的部分功能的实现

    1.3.1 层序遍历实现(BFS)

    1.3.2 求二叉树的节点个数,叶子个数和高度

    1.3.3 求二叉树第k层节点的个数

    1.3.4 查找二叉树中数值域等于x的节点并返回

    1.3.5 判断是否完全二叉树

    1.4 完整代码

    2.金句频道


    1.二叉树的链式实现

          二叉树常见的创建方式可以分为两种,一种是直接通过带空节点的先序中序后序遍历中的任何一个序列创建出来,另一种则是较为常用的不带空节点的,这种就需要先序+中序或者后序+中序的组合才能确定和创建这棵二叉树,上面两种方式都与二叉树的三种遍历(先、中、后序)遍历有关,为此我们要先来了解什么是先序中序和后序遍历。

    1.1二叉树的三种遍历方式

    1. 前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点的操作发生在遍历其左右子树之前。
    2. 中序遍历(Inorder Traversal)——访问根结点的操作发生在遍历其左右子树之中(间)。
    3. 后序遍历(Postorder Traversal)——访问根结点的操作发生在遍历其左右子树之后。

    比如,我这里有这样一棵二叉树:

    三种遍历方式,都是从根节点出发的,只是访问和输出的规则以及顺序不一致:

           对于先序遍历来说,从根节点A出发,我们每走到一棵子树,都会先将它的根节点输出,然后再分别递归其左右子树,然后再做相同的操作,直到递归结束,得到的输出序列就是先序遍历序列。

            对于中序遍历来说,还是从根节点开始遍历,但是根节点是在每一棵树的左子树“彻底”遍历完之后再输出,然后再是右子树的输出。

     对于后序遍历亦是同理,只是根在左右子树都遍历完之后输出.

           为了更好的帮助理解,我们现在直接给出三种遍历的函数实现,并在接下来采用递归调用函数栈帧的方式来帮助我们更好的理解,因为三种遍历过程思路上是一致的,一通百通,所以这里我们只是以中序遍历为例。(关于函数栈帧的相关知识,可以移步函数栈帧的创建与销毁

    1. //先序遍历
    2. void PrevOrder(BTNode* root)
    3. {
    4. if (root == NULL)
    5. {
    6. //printf("NULL ");
    7. return;
    8. }
    9. printf("%c ", root->data);
    10. PrevOrder(root->left);
    11. PrevOrder(root->right);
    12. }
    13. //中序遍历
    14. void InOrder(BTNode* root)
    15. {
    16. if (root == NULL)
    17. {
    18. //printf("NULL ");
    19. return;
    20. }
    21. InOrder(root->left);
    22. printf("%c ", root->data);
    23. InOrder(root->right);
    24. }
    25. //后序遍历
    26. void PostOrder(BTNode* root)
    27. {
    28. if (root == NULL)
    29. {
    30. //printf("NULL ");
    31. return;
    32. }
    33. PostOrder(root->left);
    34. PostOrder(root->right);
    35. printf("%c ", root->data);
    36. }

    我们还是选取上面的给出的样例,如下的二叉树:

     

    1.2 二叉树创建的两种方式

     1.2.1 已知先序(后序)+中序遍历序列

    递归建树原理解释

     代码实现:

    1. //以样例为例的先中后序数组
    2. Elemtype pre[] = { 'A','B','D','C','E','G','F' };//Elemtype看做char类型就好
    3. Elemtype in[] = { 'D','B','A','E','G','C','F' };
    4. Elemtype pos[] = { 'D','B','G','E','F','C','A'};
    5. //根据先序和中序序列确定一棵唯一的树
    6. void CreatTreewithpreandin(BTNode*& root, int prel, int prer,int inl, int inr)
    7. {
    8. int rootidx = -1;
    9. if (prel <= prer && inl <= inr)
    10. {
    11. //开始寻找该子树的根节点在中序序列中的位置
    12. for (int i = inl; i <= inr; i++)
    13. {
    14. if (in[i] == pre[prel])//先序遍历中的对应的子树区间内的第一个节点是根节点
    15. {
    16. rootidx = i;
    17. break;
    18. }
    19. }
    20. root = BuyNode(pre[prel]);
    21. //求出该子树的左子树的长度
    22. int len = rootidx - inl;
    23. //递归创建左右子树
    24. CreatTreewithpreandin(root->left, prel + 1, prel + len, inl, rootidx - 1);
    25. CreatTreewithpreandin(root->right, prel + len + 1, prer, rootidx + 1, inr);
    26. }
    27. }
    28. //根据后序和中序序列确定一棵唯一的树
    29. void CreatTreewithposandin(BTNode*& root,int posl, int posr, int inl, int inr)
    30. {
    31. int rootidx = -1;
    32. if (posl <= posr && inl <= inr)
    33. {
    34. //开始寻找该子树的根节点在中序序列中的位置
    35. for (int i = inl; i <= inr; i++)
    36. {
    37. if (in[i] == pos[posr])//后序序列的子树区间内的最后一个节点是根节点
    38. {
    39. rootidx = i;
    40. break;
    41. }
    42. }
    43. root = BuyNode(pos[posr]);
    44. //求出该子树的左子树的长度
    45. int len = rootidx - inl;
    46. //递归创建左右子树
    47. CreatTreewithposandin(root->left, posl, posl+len-1,inl,rootidx-1);
    48. CreatTreewithposandin(root->right, posl + len,posr-1, rootidx + 1, inr);
    49. }
    50. }

    1.2.2 根据带空节点的任意一个遍历序列数组来建树

           前面说我们无法根据仅有先中后序遍历中的其中之一的数组来建树,为什么这里就可以了呢?那是因为先中后序遍历只知其一,我们无法确定二叉树的孩子结构,也就是说,一个节点到底是父节点的左孩子还是右孩子我们无法确定,因为不论是左孩子还是右孩子,在遍历中得出的结果很有可能是一致的,这也就导致了我们无法唯一的确定一棵二叉树。但是,对,但是,如果存在空节点和其他节点构成完整的子树结构,简而言之,就是假设一个树没有左孩子,那么在创建时就会将该位置补上一个特殊的符号来表示空节点,这样就可以构成完整的二叉树结构。

    我们给出一个例子,比如说有一个先序数组为 "ABD##E#H##CF##G##",其中‘#’就表示空节点,

    1. // 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
    2. BTNode* BinaryTreeCreate(Elemtype* src, int n, int* idx)//其中idx传入的是数组的当前遍历位置的下标,因为值传递会因为函数栈帧的销毁而失去效果,所以此处改为传址调用,src是前序遍历数组
    3. {
    4. if (*idx >= n || src[*idx] == '#')
    5. {
    6. (*idx)++;
    7. return NULL;
    8. }
    9. BTNode* cur = (BTNode*)malloc(sizeof(BTNode));
    10. cur->data = src[*idx];
    11. (*idx)++;
    12. cur->left = BinaryTreeCreate(src, n, idx);//传地址,地址上存储的是当前遍历到的数组的下标
    13. cur->right = BinaryTreeCreate(src, n, idx);
    14. return cur;
    15. }

    1.3 二叉树的部分功能的实现

    1.3.1 层序遍历实现(BFS)

           这部分我使用了C++的queue来实现,之前我们实现过的模拟队列也可以实现,只是过程稍加繁琐,层序遍历就是按二叉树的高度遍历,从根节点开始,逐层往下遍历,我们可以使用队列,在逐层访问时将根节点的左右孩子入队,当父节点层遍历完毕时,队首元素就是下一层的遍历顺序。

    1. //层序遍历
    2. void BinaryTreeLevelOrder(BTNode* root)
    3. {
    4. //迭代法利用队列进行宽度优先遍历(C++STL)
    5. queue mp;
    6. if (!root)
    7. return;
    8. mp.push(root);
    9. while (!mp.empty())
    10. {
    11. BTNode* temp = mp.front();
    12. printf("%c ", temp->data);
    13. mp.pop();
    14. if (temp->left)
    15. mp.push(temp->left);
    16. if (temp->right)
    17. mp.push(temp->right);
    18. }
    19. }

    1.3.2 求二叉树的节点个数,叶子个数和高度

     这部分就老生常谈了,但凡会递归的,这些都不是问题啦,那我就直接......,嘿嘿~~

    1. // 二叉树结点个数
    2. int BTreeSize(BTNode* root)
    3. {
    4. return root == NULL ? 0 : BTreeSize(root->left)
    5. + BTreeSize(root->right) + 1;
    6. }
    7. // 求叶子节点的个数
    8. int BTreeLeafSize(BTNode* root)
    9. {
    10. if (root == NULL)
    11. {
    12. return 0;
    13. }
    14. if (root->left == NULL
    15. && root->right == NULL)
    16. {
    17. return 1;
    18. }
    19. return BTreeLeafSize(root->left)
    20. + BTreeLeafSize(root->right);
    21. }
    22. //二叉树的高度
    23. int BTreeHeight(BTNode* root)
    24. {
    25. if (root == NULL)
    26. return 0;
    27. int leftHeight = BTreeHeight(root->left);
    28. int rightHeight = BTreeHeight(root->right);//注意这种保存值的方式更加高效,可以画递归图证明
    29. return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    30. }

    1.3.3 求二叉树第k层节点的个数

           还是递归,求解第k层的节点,假设k=3,在二叉树有第三层的条件下,我们在递归遍历的过程中,每次进入一个父节点的孩子节点遍历时,k就减1,当k到1时就到了第k层,开始计数即可。

    1. // 二叉树第k层结点个数
    2. int BTreeLevelKSize(BTNode* root, int k)
    3. {
    4. assert(k > 0);
    5. if (root == NULL)
    6. return 0;
    7. if (k == 1)
    8. return 1;
    9. return BTreeLevelKSize(root->left, k - 1)
    10. + BTreeLevelKSize(root->right, k - 1);
    11. }

    1.3.4 查找二叉树中数值域等于x的节点并返回

           这个函数一定要画个递归逻辑图,否则很有可能调到坑里去,如果我们在递归遍历的某个节点返回的话,并不是直接结束函数返回值,而是返回的该函数的上一层调用,所以,我们在递归调用左右子树时,需要判断返回。

    1. //二叉树查找节点值为x的节点
    2. BTNode* BinaryTreeFind(BTNode* root, Elemtype x)
    3. {
    4. if (root == NULL)
    5. return NULL;
    6. if (root->data == x)
    7. return root;
    8. BTNode* left= BinaryTreeFind(root->left, x);//遍历完左子树看left的返回值
    9. if (left)
    10. return left;
    11. return BinaryTreeFind(root->right, x);//如果程序执行到了这一步,就说明有x也一定在右子树里,或者没有就可以直接返回NULL
    12. }

    1.3.5 判断是否完全二叉树

    这个问题就要考虑一会了,我们先来想想完全二叉树是什么概念来着?

    完全二叉树是一种特殊的二叉树结构,它具有以下两个特点:

    1. 满二叉树:除了叶子节点,每个节点都有两个子节点,且所有叶子节点都在同一层级上

    2. 节点分布均匀:在最后一层的节点如果不满,则只有在最后一层的右侧可以出现缺少的节点,其余各层节点都是满的,且最后一层节点必须按照从左到右的顺序排列。

           对完全二叉树最重要的定义就是叶子节点只能出现在最下层和次下层,所以我们想到可以使用队列辅助进行层次遍历——从上到下遍历所有层,每层从左到右,只有次下层和最下层才有叶子节点,其他层出现叶子节点就意味着不是完全二叉树。

    1. // 判断二叉树是否是完全二叉树
    2. bool BinaryTreeComplete(BTNode* root)
    3. {
    4. if (root == NULL)
    5. return true;//空树一定是完全二叉树
    6. queue mp;
    7. bool flag = false;
    8. mp.push(root);
    9. while (!mp.empty())
    10. {
    11. int sz = mp.size();
    12. for (int i = 0; i < sz; i++)
    13. {
    14. BTNode* temp = mp.front();
    15. mp.pop();
    16. if (temp->left != NULL)
    17. {
    18. mp.push(temp->left);
    19. if (flag)//表示已经是完全二叉树的叶子节点了(该处存在空节点,所以应该是最后了)
    20. return false;
    21. }
    22. else
    23. {
    24. //如果遇到了空节点,那么flag=true表示到了满足完全二叉树的最后的节点
    25. flag = true;
    26. }
    27. if (temp->right != NULL)
    28. {
    29. mp.push(temp->right);
    30. if (flag)//表示已经是完全二叉树的叶子节点了(该处存在空节点,所以应该是最后了)
    31. return false;
    32. }
    33. else
    34. {
    35. //如果遇到了空节点,那么flag=true表示到了满足完全二叉树的最后的节点
    36. flag = true;
    37. }
    38. }
    39. }
    40. return true;
    41. }

    1.4 完整代码

    1. #include
    2. using namespace std;
    3. typedef char Elemtype;
    4. typedef struct node {
    5. Elemtype data;
    6. struct node* left;
    7. struct node* right;
    8. }BTNode;
    9. //先中后序数组
    10. Elemtype pre[] = { 'A','B','D','C','E','G','F' };
    11. Elemtype in[] = { 'D','B','A','E','G','C','F' };
    12. Elemtype pos[] = { 'D','B','G','E','F','C','A'};
    13. Elemtype pre2[] = { 'A','B','D','#','#','E','#','H','#','#','C','F','#','#','G','#','#' };
    14. //创建新节点
    15. BTNode* BuyNode(Elemtype x)
    16. {
    17. BTNode* node = (BTNode*)malloc(sizeof(BTNode));
    18. if (node == NULL)
    19. {
    20. perror("malloc fail");
    21. return NULL;
    22. }
    23. node->data = x;
    24. node->left = NULL;
    25. node->right = NULL;
    26. return node;
    27. }
    28. //我们也可以根据带空节点的先序后序中序数组中的任意一个数组来确定一棵唯一的二叉树(这里以先序数组为例,‘N'表示此处为空)
    29. // 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
    30. BTNode* BinaryTreeCreate(Elemtype* src, int n, int* idx)
    31. {
    32. if (*idx >= n || src[*idx] == '#')
    33. {
    34. (*idx)++;
    35. return NULL;
    36. }
    37. BTNode* cur = (BTNode*)malloc(sizeof(BTNode));
    38. cur->data = src[*idx];
    39. (*idx)++;
    40. cur->left = BinaryTreeCreate(src, n, idx);//传地址,地址上存储的是当前遍历到的数组的下标
    41. cur->right = BinaryTreeCreate(src, n, idx);
    42. return cur;
    43. }
    44. //根据先序和中序序列确定一棵唯一的树
    45. void CreatTreewithpreandin(BTNode*& root, int prel, int prer,int inl, int inr)
    46. {
    47. int rootidx = -1;
    48. if (prel <= prer && inl <= inr)
    49. {
    50. //开始寻找该子树的根节点在中序序列中的位置
    51. for (int i = inl; i <= inr; i++)
    52. {
    53. if (in[i] == pre[prel])//先序遍历中的对应的子树区间内的第一个节点是根节点
    54. {
    55. rootidx = i;
    56. break;
    57. }
    58. }
    59. root = BuyNode(pre[prel]);
    60. //求出该子树的左子树的长度
    61. int len = rootidx - inl;
    62. //递归创建左右子树
    63. CreatTreewithpreandin(root->left, prel + 1, prel + len, inl, rootidx - 1);
    64. CreatTreewithpreandin(root->right, prel + len + 1, prer, rootidx + 1, inr);
    65. }
    66. }
    67. //根据后序和中序序列确定一棵唯一的树
    68. void CreatTreewithposandin(BTNode*& root,int posl, int posr, int inl, int inr)
    69. {
    70. int rootidx = -1;
    71. if (posl <= posr && inl <= inr)
    72. {
    73. //开始寻找该子树的根节点在中序序列中的位置
    74. for (int i = inl; i <= inr; i++)
    75. {
    76. if (in[i] == pos[posr])//后序序列的子树区间内的最后一个节点是根节点
    77. {
    78. rootidx = i;
    79. break;
    80. }
    81. }
    82. root = BuyNode(pos[posr]);
    83. //求出该子树的左子树的长度
    84. int len = rootidx - inl;
    85. //递归创建左右子树
    86. CreatTreewithposandin(root->left, posl, posl+len-1,inl,rootidx-1);
    87. CreatTreewithposandin(root->right, posl + len,posr-1, rootidx + 1, inr);
    88. }
    89. }
    90. //先序遍历
    91. void PrevOrder(BTNode* root)
    92. {
    93. if (root == NULL)
    94. {
    95. //printf("NULL ");
    96. return;
    97. }
    98. printf("%c ", root->data);
    99. PrevOrder(root->left);
    100. PrevOrder(root->right);
    101. }
    102. //中序遍历
    103. void InOrder(BTNode* root)
    104. {
    105. if (root == NULL)
    106. {
    107. //printf("NULL ");
    108. return;
    109. }
    110. InOrder(root->left);
    111. printf("%c ", root->data);
    112. InOrder(root->right);
    113. }
    114. //后序遍历
    115. void PostOrder(BTNode* root)
    116. {
    117. if (root == NULL)
    118. {
    119. //printf("NULL ");
    120. return;
    121. }
    122. PostOrder(root->left);
    123. PostOrder(root->right);
    124. printf("%c ", root->data);
    125. }
    126. //层序遍历
    127. void BinaryTreeLevelOrder(BTNode* root)
    128. {
    129. //迭代法利用队列进行宽度优先遍历(C++STL)
    130. queue mp;
    131. if (!root)
    132. return;
    133. mp.push(root);
    134. while (!mp.empty())
    135. {
    136. BTNode* temp = mp.front();
    137. printf("%c ", temp->data);
    138. mp.pop();
    139. if (temp->left)
    140. mp.push(temp->left);
    141. if (temp->right)
    142. mp.push(temp->right);
    143. }
    144. }
    145. // 二叉树结点个数
    146. int BTreeSize(BTNode* root)
    147. {
    148. return root == NULL ? 0 : BTreeSize(root->left)
    149. + BTreeSize(root->right) + 1;
    150. }
    151. // 求叶子节点的个数
    152. int BTreeLeafSize(BTNode* root)
    153. {
    154. if (root == NULL)
    155. {
    156. return 0;
    157. }
    158. if (root->left == NULL
    159. && root->right == NULL)
    160. {
    161. return 1;
    162. }
    163. return BTreeLeafSize(root->left)
    164. + BTreeLeafSize(root->right);
    165. }
    166. //二叉树的高度
    167. int BTreeHeight(BTNode* root)
    168. {
    169. if (root == NULL)
    170. return 0;
    171. int leftHeight = BTreeHeight(root->left);
    172. int rightHeight = BTreeHeight(root->right);
    173. return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    174. }
    175. // 二叉树第k层结点个数
    176. int BTreeLevelKSize(BTNode* root, int k)
    177. {
    178. assert(k > 0);
    179. if (root == NULL)
    180. return 0;
    181. if (k == 1)
    182. return 1;
    183. return BTreeLevelKSize(root->left, k - 1)
    184. + BTreeLevelKSize(root->right, k - 1);
    185. }
    186. // 判断二叉树是否是完全二叉树
    187. bool BinaryTreeComplete(BTNode* root)
    188. {
    189. if (root == NULL)
    190. return true;//空树一定是完全二叉树
    191. queue mp;
    192. bool flag = false;
    193. mp.push(root);
    194. while (!mp.empty())
    195. {
    196. int sz = mp.size();
    197. for (int i = 0; i < sz; i++)
    198. {
    199. BTNode* temp = mp.front();
    200. mp.pop();
    201. if (temp->left != NULL)
    202. {
    203. mp.push(temp->left);
    204. if (flag)//表示已经是完全二叉树的叶子节点了(该处存在空节点,所以应该是最后了)
    205. return false;
    206. }
    207. else
    208. {
    209. //如果遇到了空节点,那么flag=true表示到了满足完全二叉树的最后的节点
    210. flag = true;
    211. }
    212. if (temp->right != NULL)
    213. {
    214. mp.push(temp->right);
    215. if (flag)//表示已经是完全二叉树的叶子节点了(该处存在空节点,所以应该是最后了)
    216. return false;
    217. }
    218. else
    219. {
    220. //如果遇到了空节点,那么flag=true表示到了满足完全二叉树的最后的节点
    221. flag = true;
    222. }
    223. }
    224. }
    225. return true;
    226. }
    227. //二叉树查找节点值为x的节点
    228. BTNode* BinaryTreeFind(BTNode* root, Elemtype x)
    229. {
    230. if (root == NULL)
    231. return NULL;
    232. if (root->data == x)
    233. return root;
    234. BTNode* left= BinaryTreeFind(root->left, x);//遍历完左子树看left的返回值
    235. if (left)
    236. return left;
    237. return BinaryTreeFind(root->right, x);//如果程序执行到了这一步,就说明有x也一定在右子树里,或者没有就可以直接返回NULL
    238. }
    239. //二叉树的销毁
    240. void BinaryTreeDestory(BTNode*& root)//引用可以用二级指针代替
    241. {
    242. if (root)
    243. {
    244. BinaryTreeDestory(root->left);
    245. BinaryTreeDestory(root->right);
    246. free(root);
    247. root = NULL;
    248. }
    249. }
    250. int main()
    251. {
    252. BTNode* root=NULL;
    253. //根据先序和中序建树
    254. /*CreatTreewithpreandin(root, 0, 6, 0, 6);
    255. printf("后序遍历序列为:->\n");
    256. PostOrder(root);*/
    257. //根据后序和中序建树
    258. /*CreatTreewithposandin(root, 0, 6, 0, 6);
    259. printf("先序遍历序列为:->\n");
    260. PrevOrder(root);*/
    261. //根据带空节点的先序序列建树
    262. int idx = 0;
    263. root=BinaryTreeCreate(pre2,17,&idx);
    264. printf("先序遍历序列为:->\n");
    265. PrevOrder(root);
    266. printf("\n层序遍历序列为:->\n");
    267. BinaryTreeLevelOrder(root);
    268. return 0;
    269. }

    2.金句频道

           你就应该满脑子都是前途,不用在意别人的看法,不再害怕别人讨厌自己,不在畏手畏脚忧心忡忡,也不会在睡前反复回忆白天的行为,是否会让对方产生误解。要么努力往上爬,要么永远烂在底层里,这就是现实,没有可以依靠的人,那就自己拼命地努力。

     

  • 相关阅读:
    gdb结合valgrind一起使用
    在AOSP中根据设备特性进行个性化定制:利用getPackageManager().hasSystemFeature()接口实现
    框架好坏 评判的标准
    S7-200SMART PLC模拟量应用及创建库文件的具体方法
    Java、检查顺序
    Java项目:SSM学生选课管理系统
    获取HTML元素的scrollHeight属性
    使用Spring Boot和Spring Security保护你的应用
    什么是 Linux Mint,它比 Ubuntu 好在哪里?
    cookie、session、token
  • 原文地址:https://blog.csdn.net/m0_64707620/article/details/130899058