【Leetcode】二叉树的最小深度

题目:

给定一个二叉树,找出其最小深度。

注意最小深度的定义!

最小深度从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

一、递归法

时间复杂度:O(n)。需要遍历每一个节点。

空间复杂度:最差情况下,当一棵树是非平衡树的时候,例如每个节点都只有一个孩子,树的高度为n,会产生n次递归调用,因此栈的空间开销是O(N)。但在最好情况下,树的高度只有log(n),栈的空间开销是O(log(N))。

/**
 * 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 == NULL)
            return 0;
        
        if( (root->left == NULL) && (root->right == NULL) )
            return 1;
        
        int depthL = INT_MAX;
        int depthR = INT_MAX;
        
        if(root->left != NULL)
            depthL = minDepth(root->left);
        if(root->right != NULL)
            depthR = minDepth(root->right);
        
        int depth = min( depthL, depthR ) + 1;
        return depth;
    }
};

二、宽度优先搜索

使用FIFO的数据结构queue存储树节点,从而实现对树节点自上而下的遍历。

时间复杂度:O(N)。完全二叉树的情况下,需要对 n/2 个节点进行遍历。非平衡树的情况下,例如每个节点只有1个孩子节点,则需要遍历所有节点。

空间复杂度:O(N)。完全二叉树的情况下,queue容器中最多需要存储 n/2 个节点。非平衡树的情况下,例如每个节点只有1个孩子节点,则queue容器中最多只存储1个节点。

/**
 * 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 == NULL)
            return 0;
        
        queue<TreeNode*> q;
        q.push(root);
        int depth = 0;
        
        while(!q.empty()) {
            int len = q.size();
            
            for(int i = 0; i < len; ++i) {
                TreeNode* node = q.front();
                q.pop();
                
                int num = 0;
                
                if(node->left != NULL) {
                    q.push(node->left);
                    num += 1;
                }
                if(node->right != NULL) {
                    q.push(node->right);
                    num += 1;
                }
                
                if(num == 0)
                    return depth + 1;
            }
            depth++;
        }
        return depth;
    }
};
原文地址:https://www.cnblogs.com/gdut-gordon/p/11647108.html