Minimum Depth of Binary Tree--LeetCode

今天药忘吃喽~ 2022-08-07 11:56 107阅读 0赞

题目:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

思路:这里递归就需要注意一些东西了,对于非递归来说,只要发现有一个节点没有左子树同时也没有右子树,那么这个就是节点所在层次就是目标

  1. int MinDepth(BinTree* root)
  2. {
  3. if(root == NULL)
  4. return 0;
  5. if(root->left == NULL)
  6. return MinDepth(root->right)+1;
  7. if(root->right == NULL)
  8. return MinDepth(root->left)+1;
  9. return min(MinDepth(root->left),MinDepth(root->right))+1;
  10. }
  11. int MinDepth_second(BinTree* root)
  12. {
  13. if(root == NULL)
  14. return 0;
  15. BinTree* node;
  16. deque<BinTree*> de;
  17. int num;
  18. int curnum=0;
  19. int level=0;
  20. de.push_back(root);
  21. num=1;
  22. while(!de.empty())
  23. {
  24. node = de.front();
  25. de.pop_front();
  26. num--;
  27. if(node->left==NULL && node->right == NULL)
  28. return level+1;
  29. if(node->left != NULL)
  30. {
  31. de.push_back(node->left);
  32. curnum++;
  33. }
  34. if(node->right !=NULL)
  35. {
  36. de.push_back(node->right);
  37. curnum++;
  38. }
  39. if(num == 0)
  40. {
  41. num = curnum;
  42. curnum=0;
  43. level++;
  44. }
  45. }
  46. return level;
  47. }

发表评论

表情:
评论列表 (有 0 条评论,107人围观)

还没有评论,来说两句吧...

相关阅读