这是林永吉的算法题仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.6 KiB

  1. #include "../include/5_MinDepth.h"
  2. //题目:求一个二叉树的最小深度
  3. //思路:1.深度优先算法,优先深度查找,直到为空,逐层返回Depth + 1,
  4. // 2.左子树长度记为L1,右子树长度记为L2,然后返回较小的一个
  5. int MinDepth(struct TreeNode* root)
  6. {
  7. int Depth = 0;
  8. int L1, L2;
  9. if (NULL == root) { //如果根节点为空,返回0
  10. return 0;
  11. } //如果左右子树为空,返回1
  12. else if ((NULL == root->left) && (NULL == root->right)) {
  13. return 1;
  14. } //如果左子树不为空,右子树为空,继续搜索左子树
  15. else if ((NULL != root->left) && (NULL == root->right)) {
  16. Depth = MinDepth(root->left);
  17. } //如果左子树为空,右子树不为空,继续搜索右子树
  18. else if ((NULL == root->left) && (NULL != root->right)) {
  19. Depth = MinDepth(root->right);
  20. } //如果都不为空,则两边搜索
  21. else {
  22. L1 = MinDepth(root->left);
  23. L2 = MinDepth(root->right);
  24. Depth = fmin(L1, L2);//把左右子树中,深度较小的一个给Depth
  25. }
  26. return Depth + 1;//每次搜索完,把搜索到的结果进行累加
  27. }
  28. //创建一棵二叉树,入参为字符串数组。
  29. TreeNode* CreatBitTree(char str[][50], int return_count)
  30. { //如果传进来的字符串数组为空,则返回空
  31. if (str == NULL || return_count <= 0) {
  32. return NULL;
  33. }//给给根节点开辟一片空间
  34. TreeNode* head = (TreeNode*)malloc(sizeof(TreeNode));
  35. if (NULL == head) {//如果内存申请失败,返回NULL
  36. return NULL;
  37. }//给根节点的数据域赋值,
  38. head->val = _ttoi(str[0]);
  39. CreatBitTreeNode1(str, return_count, head, 0);//通过调用函数,给根节点以外的子树赋值
  40. return head;//返回根节点
  41. }
  42. //函数功能是给根节点以外的子树赋值,入参为字符串数组、根节点、标志位
  43. void CreatBitTreeNode1(char str[][50], int return_count, TreeNode* cur, int curIndex)
  44. { //赋值前判空
  45. if (str == NULL || return_count <= 0 || cur == NULL || curIndex >= return_count || curIndex < 0) {
  46. return;
  47. }//递归赋值
  48. int last = return_count - 1;
  49. if ((2 * curIndex + 1 <= last) && strcmp(str[2 * curIndex + 1], "NULL")) {
  50. cur->left = (TreeNode*)malloc(sizeof(TreeNode));
  51. if (NULL == cur->left) {
  52. return;
  53. }
  54. cur->left->val = _ttoi(str[2 * curIndex + 1]);
  55. }
  56. else {
  57. cur->left = NULL;
  58. }
  59. if ((2 * curIndex + 2 <= last) && strcmp(str[2 * curIndex + 2], "NULL")) {
  60. cur->right = (TreeNode*)malloc(sizeof(TreeNode));
  61. if (NULL == cur->right) {
  62. return;
  63. }
  64. cur->right->val = _ttoi(str[2 * curIndex + 2]);
  65. }
  66. else {
  67. cur->right = NULL;
  68. }
  69. CreatBitTreeNode1(str, return_count, cur->left, 2 * curIndex + 1);
  70. CreatBitTreeNode1(str, return_count, cur->right, 2 * curIndex + 2);
  71. }
  72. //释放二叉树
  73. void free_tree(TreeNode* T)//后序释放
  74. {
  75. if (!T) {
  76. return;
  77. }
  78. if (T->left) {
  79. free_tree(T->left);
  80. }
  81. if (T->right) {
  82. free_tree(T->right);
  83. }
  84. if (T) {
  85. free(T);
  86. T = NULL;
  87. }
  88. }