111. Minimum Depth of Binary Tree

缺乏、安全感 2022-05-04 10:28 301阅读 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its minimum depth = 2.

方法一:递归

  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 minDepth(TreeNode* root) {
  13. if(root == NULL)
  14. return 0;
  15. if(root->left != NULL && root->right!= NULL)
  16. return 1 + min(minDepth(root->left), minDepth(root->right));
  17. else if(root->left==NULL)
  18. return 1 + minDepth(root->right);
  19. else if(root->right== NULL)
  20. return 1 + minDepth(root->left);
  21. }
  22. };

方法2:非递归

  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 minDepth(TreeNode* root) {
  13. if(root == NULL)
  14. return 0;
  15. queue<TreeNode*> node;
  16. node.push(root);
  17. int count=0;
  18. while(!node.empty())
  19. {
  20. count++;
  21. int len = node.size();
  22. for(int i=0;i<len;i++)
  23. {
  24. root = node.front();
  25. node.pop();
  26. if(root->left == NULL && root->right == NULL)
  27. return count;
  28. if(root->left)
  29. node.push(root->left);
  30. if(root->right)
  31. node.push(root->right);
  32. }
  33. }
  34. return count;
  35. }
  36. };

发表评论

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

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

相关阅读