Minimum Depth of Binary Tree

描述

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. // Minimum Depth of Binary Tree
  2. // 递归版,时间复杂度O(n),空间复杂度O(logn)
  3. class Solution {
  4. public:
  5. int minDepth(const TreeNode *root) {
  6. return minDepth(root, false);
  7. }
  8. private:
  9. static int minDepth(const TreeNode *root, bool hasbrother) {
  10. if (!root) return hasbrother ? INT_MAX : 0;
  11. return 1 + min(minDepth(root->left, root->right != NULL),
  12. minDepth(root->right, root->left != NULL));
  13. }
  14. };

迭代版

  1. // Minimum Depth of Binary Tree
  2. // 迭代版,时间复杂度O(n),空间复杂度O(logn)
  3. class Solution {
  4. public:
  5. int minDepth(TreeNode* root) {
  6. if (root == nullptr)
  7. return 0;
  8. int result = INT_MAX;
  9. stack<pair<TreeNode*, int>> s;
  10. s.push(make_pair(root, 1));
  11. while (!s.empty()) {
  12. auto node = s.top().first;
  13. auto depth = s.top().second;
  14. s.pop();
  15. if (node->left == nullptr && node->right == nullptr)
  16. result = min(result, depth);
  17. if (node->left && result > depth) // 深度控制,剪枝
  18. s.push(make_pair(node->left, depth + 1));
  19. if (node->right && result > depth) // 深度控制,剪枝
  20. s.push(make_pair(node->right, depth + 1));
  21. }
  22. return result;
  23. }
  24. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/binary-tree/recursion/minimum-depth-of-binary-tree.html