跳转至

111.Minimum Depth of Binary Tree

Tags: Easy Depth-first Search Breadth-first Search

Links: 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.

Note: A leaf is a node with no children.

Example:

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

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


/**
 * 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) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!root) return 0;
        if (!root -> left && !root -> right) return 1;

        int l = INT_MAX - 1, r = INT_MAX - 1;
        if (root -> left) l = minDepth(root -> left);
        if (root -> right) r = minDepth(root -> right);

        return 1 + min(l, r);
    }
};

迭代解法,仍然是层序遍历的思路,当一个节点的左右节点都为空的时候,表明此节点是叶节点,直接返回即可。

/**
 * 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) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!root) return 0;
        queue<TreeNode *> q;
        q.push(root);
        int level = 0;
        while (!q.empty()) {
            int n = q.size();
            ++level;
            for (int i = 0; i < n; ++i) {
                TreeNode *tmp = q.front(); q.pop();
                if (!tmp -> left && !tmp -> right) return level;
                if (tmp -> left) q.push(tmp -> left);
                if (tmp -> right) q.push(tmp -> right);
            }
        }

        return level;
    }
};