78:Minimum Depth of Binary Tree

    xiaoxiao2021-03-25  105

    题目: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:可以自底向上,从叶节点开始计算最小深度

    代码如下:

    // 递归版,时间复杂度 O(n),空间复杂度 O(logn) // 自底向上,从叶节点开始计算树的最小深度 class Solution { public: int minDepth(TreeNode* root) { if (!root) return 0; if (!root -> left && !root -> right) return 1; else if (root -> left && root -> right) return min(minDepth(root -> left), minDepth(root -> right)) + 1; else { if (root -> left) return minDepth(root -> left) + 1; else return minDepth(root -> right) + 1; } };

    解析2:自顶向下,从根节点开始计算树的最小深度,代码如下:

    // 迭代版,时间复杂度 O(n),空间复杂度 O(log n) // 自顶向下,从根节点开始计算树的最小深度 class Solution { public: int minDepth(TreeNode* root) { if (!root) return 0; int result = INT_MAX; stack<pair<TreeNode*, int>> s; s.push(make_pair(root, 1)); while (!s.empty()) { auto node = s.top().first; auto depth = s.top().second; s.pop(); if (!node -> left && !node -> right) result = min(result, depth); if (root -> left && result > depth) s.push(make_pair(node -> left, depth + 1)); if (node -> right && result > depth) s.push(make_pair(node -> right, depth + 1)); } return result; } }
    转载请注明原文地址: https://ju.6miu.com/read-17635.html

    最新回复(0)