Leetcode NO.111 Minimum Depth of Binary Tree
2015-07-23 07:09
381 查看
本题题目要求如下:
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.
这道题是一道很简单的题目,基本思想就是DFS,但是DFS要多一个参数来测定该层的层数,再定义一个全局变量来表示此时的最小层数,并不断更新它即可,代码如下所示:
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.
这道题是一道很简单的题目,基本思想就是DFS,但是DFS要多一个参数来测定该层的层数,再定义一个全局变量来表示此时的最小层数,并不断更新它即可,代码如下所示:
/** * 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; } dfs(root, 1); return globalMin; } private: int globalMin = INT_MAX; void dfs(TreeNode* root, int level) { if (level >= globalMin) { return; } if (root->left == nullptr and root->right == nullptr) { globalMin = level; } if (root->left != nullptr) { dfs(root->left, level+1); } if (root->right != nullptr) { dfs(root->right, level+1); } } };
相关文章推荐
- Java 中最常见的 5 个错误
- 滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(持续更新...)
- 7.23翻倍奖励——滴滴快车单(成交率≥80%,≥10指派单)
- 2015年07月21日第13天笔记
- 7.23翻倍奖励——滴滴快车单(成交率≥60%,≥5指派单)
- 后台系统重构碰到的问题
- 7.23翻倍奖励——滴滴快车单(成交率≥50%,≥1指派单)
- C Objcet类
- programming-challenges A multiplication game (110505) 题解
- Git 使用中的问题
- Scala中隐式转换内幕操作规则揭秘
- 多线程(线程的概述,创建线程,控制线程,线程同步,线程池)
- 如何打印运行时加载类的包名(物理包名,不是路径)
- 优步司机如何联系客服?uber客服渠道,Uber优步司机客服渠道
- LeetCode Happy Number
- LeetCode Happy Number
- spring官网下载jar包
- UberX及以上级别车奖励政策(优步北京第四组)
- UberX及以上级别车奖励政策(优步北京第二、三组)
- UberX及以上级别车奖励政策(优步北京第一组)