【LeetCode】111. Minimum Depth of Binary Tree解法及注释,Java,C++,DFS
2016-05-04 09:50
615 查看
111. Minimum Depth of Binary Tree
Total
Accepted: 104964 Total
Submissions: 342426 Difficulty: Easy
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.
【分析】
给定一个二叉树,要求其最小深度,这和【LeetCode】104求最大深度的方法并没有本质的不同,在104题中我提供了一种DFS的方法,但就此题并不能直接套用,毕竟思想有差异:1.初始条件差异,我们将最小深度的初始值设为INT_MAX(Java中为Integer.MAX_VALUE);2.深度值更新条件差异,只有到达叶子结点才更新。此外,我在网上看到一个十分简洁的算法,采用的是递归的思想,这里我直接给出了。
【DFS版】
class Solution { public: int minDepth(TreeNode* root) { if(root==NULL)return 0; int minDepth=INT_MAX; DFS(root,0,minDepth); return minDepth; } void DFS(TreeNode* root,int depth,int &minDepth) { if(root==NULL)return; if(root->left==NULL&&root->right==NULL) { if(depth+1<minDepth)minDepth=depth+1; } else { DFS(root->left,depth+1,minDepth); DFS(root->right,depth+1,minDepth); } } };
【C++版】
/** * 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; int LDepth=minDepth(root->left); int RDepth=minDepth(root->right); if(LDepth==0&&RDepth==0) return 1; if(LDepth==0) LDepth=INT_MAX; if(RDepth==0) RDepth=INT_MAX; return min(LDepth,RDepth)+1; } };
【Java版】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public int minDepth(TreeNode root)
{
if(root==null)return 0;
if(root.left==null&&root.right==null)return 1;
int LDepth=minDepth(root.left);
int RDepth=minDepth(root.right);
if(LDepth==0)
LDepth=Integer.MAX_VALUE;
if(RDepth==0)
RDepth=Integer.MAX_VALUE;
return Math.min(LDepth,RDepth)+1;
}
}
相关文章推荐
- 学习笔记之深入浅出MFC 第8章 C++重要性质---Template
- MOOC北京理工《C语言程序设计(上)》第6周第1题:数字正方形
- C++11 模板元编程初探: 在编译期间确定斐波那契数列
- 我的c\c++之旅(四)
- c++ primer(第五版)学习笔记及习题答案代码版(第四章)表达式
- c++编写简单的计算器程序
- 【C语言】输入一个整数N,求N以内的素数之和
- c语言函数可变参数 例
- C++中注册表操作
- 学习笔记之深入浅出MFC 第8章 C++重要性质---异常处理(Exception Handing)
- windows下使用gvim搭建简单的IDE编译环境(支持C/C++/Python等)
- C++输入输出运算符重载(“>>”“<<”)
- C++实现一个按键精灵
- MOOC北京理工《C语言程序设计(上)》第5周第3题:求最小m值
- 成为C++高手之第一个程序
- C++11 多线程
- 【步兵 c++】 多态&虚函数
- C++11 正则表达式——实例3
- C++11 正则表达式——实例2
- 关于模板编程的一个例子 来自深度探索c++对象模型