111. Minimum Depth of Binary Tree

https://leetcode.com/problems/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.

Thoughts

返回二叉树从root到leaf最短的路径长度。分治,返回子树中深度小的那个并加上当前的边,但当子树有个空时由于没有叶结点,忽略。

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        if (root->left != nullptr && root->right == nullptr) return minDepth(root->left) + 1;
        if (root->right != nullptr && root->left == nullptr) return minDepth(root->right) + 1;
        return min(minDepth(root->left), minDepth(root->right)) + 1;
    }
};

Analysis

时间复杂度O(n).

Ver.2

iterative版分治. 当是叶节点时, 检查下stack长度, 因为stack存的是当前path.

Last updated

Was this helpful?