LeetCode刷题(C++)——Maximum Depth of Binary Tree(Easy)

小灰灰 2022-06-17 14:44 185阅读 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 a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int getDepth(TreeNode* p)
  13. {
  14. if(p==NULL)
  15. {
  16. return 0;
  17. }
  18. int LD,RD;
  19. LD = getDepth(p->left);
  20. RD =getDepth(p->right);
  21. return (LD>RD?LD:RD)+1;
  22. }
  23. int maxDepth(TreeNode* root) {
  24. return getDepth(root);
  25. }
  26. };

一种更简便的实现方法

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int maxDepth(TreeNode* root) {
  13. return root? max(maxDepth(root->left),maxDepth(root->right))+1:0;
  14. }
  15. };

发表评论

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

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

相关阅读