LeetCode刷题(C++)——Minimum Depth if Binary Tree(Easy)

野性酷女 2022-06-17 14:39 208阅读 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. /*
  2. Definition for binary tree
  3. struct TreeNode
  4. {
  5. int val;
  6. TreeNode* left;
  7. TreeNode* right;
  8. TreeNode(int x):val(x),left(NULL),right(NULL){}
  9. };
  10. */
  11. class Solution {
  12. public:
  13. int getDepth(TreeNode* p)
  14. {
  15. if (p == NULL)
  16. return 0;
  17. if (p->left == NULL&&p->right == NULL)
  18. return 1;
  19. int LD = INT_MAX;
  20. int RD = INT_MAX;
  21. if (p->left)
  22. LD = getDepth(p->left)+1;
  23. if (p->right)
  24. RD = getDepth(p->right)+1;
  25. return (LD > RD) ? RD : LD;
  26. }
  27. int run(TreeNode *root) {
  28. int mindepth = getDepth(root);
  29. return mindepth;
  30. }
  31. };

发表评论

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

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

相关阅读