[牛客网-Leetcode] #树 较难 minimum-depth-of-binary-tree

二叉树的最小深度 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.

示例

输入

{1,2,3,4,5}

输出

2

解题思路

二叉树操作主要还是利用尾递归或者循环遍历这两种思路,进而涉及DFS(主要利用递归或者栈实现)或者BFS(主要利用队列实现)。剩下的只需要按照这些思路即可。

思路1:递归

  • 首先明确run函数的作用:求出以root为根节点的树的最小深度
  • 递归,若为空树,返回0
  • 若左子树为空,右子树不空,返回右子树最小深度+1
  • 若左子树不空,右子树为空,返回左子树最小深度+1
  • 若左右子树均为空,则返回1
  • 若左右子树均不为空,返回左右子树中的最小深度+1
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
    
    
public:
    int run(TreeNode* root) {
    
    
        if(root == NULL) return 0;
        //左子树不空,右子树空
        if(root -> left && !root -> right) {
    
    
            return run(root -> left) + 1;
        }
        //左子树空,右子树不空
        if(!root -> left && root -> right) {
    
    
            return run(root -> right) + 1;
        }
        //左右子树均为空
        if(!root -> left && !root -> right) {
    
    
            return 1;
        }
        //左右子树均不空
        return min(run(root -> left), run(root -> right)) + 1;
        
    }
};

思路2:BFS层序遍历

  • 按照层序遍历的思想,一旦找到第一个叶节点,它肯定是最短的。
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
    
    
public:
    int run(TreeNode* root) {
    
    
        if(root == NULL) return 0;
        int level(1);  //初始最小深度为1
        queue<TreeNode*> myque;
        myque.push(root);
        
        while(!myque.empty()) {
    
    
            int size = myque.size();  //记录每一层的节点数
            for(int i = 0; i < size; i ++) {
    
    
                TreeNode* temp = myque.front();
                myque.pop();
                //如果找到第一个叶节点,则直接返回最小深度
                if(!temp -> left && !temp -> right) return level;
                if(temp -> left) myque.push(temp -> left);
                if(temp -> right) myque.push(temp -> right);
            }
            level ++;  //进入下一层时最小深度加一
        }
        return level;
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106882820