Leetcode-minimum-depth-of-binary-tree
来源:互联网 发布:cf免费卡枪带软件 编辑:程序博客网 时间:2024/06/05 07:23
题目描述
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.
题目意思是比较明确的,求一个树的最短路径。
需要考虑的情况比较多:如果根为空,根的左孩子为空,根的右孩子为空,根的的左右孩子都为空,根的左右孩子 都不为空。
不同情况下对应的结果是不同的,不能一概而论。代码如下:
* public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int run(TreeNode root) { if(root == null) return 0; if(root.left==null && root.right==null) return 1; if(root.left==null) return run(root.right)+1; if(root.right==null) return run(root.left)+1; return Math.min(run(root.left), run(root.right))+1; }}
如代码所示:
根为空时,返回0;根的左孩子为空,返回根的右孩子深度+1;根的右孩子为空,返回根的左孩子深度+1;根的左右孩子都为空,返回1;根的左右孩子都不为空,返回根的左孩子深度与右孩子深度的小者+1。
0 0
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- OpenGL学习笔记5:着色器
- POJ 2182 Lost Cows
- 向量夹角顺时针或逆时针,交叉口向左拐向右拐的问题
- 第3章 操作符
- Kinect基础之在WinForm(C#)中显示彩色数据和深度数据
- Leetcode-minimum-depth-of-binary-tree
- STL基础(二)
- 第4章 控制执行流程
- MongoDB主从复制
- 垃圾ac自动模板
- 第5章 初始化与清理
- EL表达式
- Mac添加环境变量全面解读
- 【JZOJ4597】现世斩