LeetCode – 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.

解题:

      深度优先搜索方式,分别找到左右子树最小+1;广度优先搜索,逐层遍历找到叶子节点返回层数。 

实现:

  • DFS  空间复杂度O(N)    时间复杂度 O(N)
          
class Solution {
public:

    int minDepth(TreeNode* root) {
        if(!root)  return 0;
        if(!root->left)  return 1+minDepth(root->right);
        if(!root->right) return 1+minDepth(root->left);
        return 1+min(minDepth(root->left), minDepth(root->right));
    }
};

实现:

  • BFS  空间复杂度O(N)    时间复杂度 O(N)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

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

Be First to Comment

发表回复