当前位置:网站首页>Leetcode 111. 二叉树的最小深度
Leetcode 111. 二叉树的最小深度
2022-07-21 09:53:00 【LuZhouShiLi】
Leetcode 111. 二叉树的最小深度
题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
思路
- 确定递归函数的参数和返回值:参数就是二叉树的节点,返回值就是最小深度
- 确定终止条件,节点为空,返回0
- 确定单层递归逻辑:左子树为空,右子树不为空,说明当前节点并不是叶子节点,所以继续递归右子树;右子树为空,左子树不为空,继续递归左子树。
代码
/** * 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 getDepth(TreeNode* node)
{
if(node == NULL)
{
return 0;
}
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
// 左子树为空 右子树不为空 右子树深度加一
if(node->left == NULL && node->right != NULL)
{
return 1 + rightDepth;
}
// 右子树为空 左子树不为空
if(node->left != NULL && node->right == NULL)
{
return 1 + leftDepth;
}
int result = 1 + min(leftDepth,rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
边栏推荐
- 【西瓜书学习】1、决策树
- 已解决(selenium操作火狐浏览器报错)TypeError: __init__() got an unexpected keyword argument ‘firefox_options‘
- VLAN与三层交换机
- DHCP protocol
- 古中国文明
- Learn STM32, starting with the framework design of Hal library
- Resolved (selenium operation Firefox browser error) typeerror:__ init__ () got an unexpected keyword argument ‘firefox_ options‘
- 请问:flink 1.14.5兼容mysql cdc 2.1.0吗
- Win10 install NVM
- [watermelon book learning] 1. Decision tree
猜你喜欢
SQL每日一练(牛客新题库)——第3天: 条件查询
Network layer protocol introduction
Skywalking custom link tracking and performance analysis
[Development Tutorial 4] crazy shell · humanoid hip-hop robot PC upper computer online debugging
[development tutorial 6] AI voice face recognition (Conference recorder / face punch card machine) - serial port
Gateway integrates sentinel to implement flow restriction rules for routing
un7.20:如何同时将关联表中的两个属性展示出来?
web安全入门-TCP压力测试与防御
Skywalking integrated logging framework, alarm and high availability cluster construction
Gateway route assertion factory, filter factory, cross domain processing
随机推荐
身份证号码中间位数隐藏
Commutateur H3C pour voir les commandes associées
QT | QT project documents Detailed explanation of pro file
MySQL. Pas de fichier ou de répertoire
SQL每日一练(牛客新题库)——第3天: 条件查询
Basic principle and configuration of switch
CTF problem solving ideas
辛丑年之立冬
mysql.h: No such file or directory
Creation of gateway routing service
[H3C device networking configuration]
Sentinel theoretical knowledge and introduction
Fluent introduces the graphic verification code and retains the sessionid
Anti sandbox method
H3C交换机查看相关的命令
网络布线与数制转换
H3C switch view related commands
RichView Table 表格对齐
交换机基本原理与配置
【微信小程序】textarea多行输入框(80/100)