【LeetCode-树】二叉树的最小深度

题目描述

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:

给定二叉树 [3,9,20,null,null,15,7],
    3
   / 
  9  20
    /  
   15   7
返回它的最小深度  2.

题目链接: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

思路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==nullptr) return 0;

        int leftDepth = minDepth(root->left)+1;
        int rightDepth = minDepth(root->right)+1;
        
        if(leftDepth==1) return rightDepth; // 左子树为空
        else if(rightDepth==1) return leftDepth;  // 右子树为空
        else return min(leftDepth, rightDepth);  // 都不为空
    }
};

也可以换一种写法:

/**
 * 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) return minDepth(root->right)+1;
        else if(root->right==nullptr) return minDepth(root->left)+1;
        else{
            return min(minDepth(root->left), minDepth(root->right))+1;
        }
    }
};
  • 时间复杂度:O(n)
    n 为节点个数;
  • 空间复杂度:O(h)
    h 为树高。

思路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) {
        if(root==nullptr) return 0;

        queue<TreeNode*> q;
        q.push(root);
        int depth = 1;
        while(!q.empty()){
            int nodeNums = q.size();
            for(int i=0; i<nodeNums; i++){
                TreeNode* node = q.front(); q.pop();
                if(node->left==nullptr && node->right==nullptr) return depth; // 遇到了叶子结点,到达最低深度
                if(node->left!=nullptr) q.push(node->left);
                if(node->right!=nullptr) q.push(node->right);
            }
            depth++;
        }
        return depth;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
原文地址:https://www.cnblogs.com/flix/p/13138215.html