Minimum Depth of Binary Tree
2015-06-06 17:39
417 查看
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即可,注意判断递归的出口。
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node
思路:求一棵树的最小深度可以转化为求左子树和右子树的最小深度,然后加上1即可,注意判断递归的出口。
/** * 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; if(root.left==null) return minDepth(root.right)+1; if(root.right==null) return minDepth(root.left)+1; int left=minDepth(root.left); int right=minDepth(root.right); return Math.min(left,right)+1; } }
相关文章推荐
- Android25图灵聊天项目------在代码中拿到资源文件string.xml中的数据
- android之ListView使用
- 优化算法——拟牛顿法之L-BFGS算法
- ss
- 随便敲敲算法(三)
- LeetCode Reverse Integer
- 我们iTailor智能衣橱项目想法v1.0
- Leetcode Longest Common Prefix (java)
- LLL XXX
- 10个令人惊讶的NodeJS开源项目
- 孤儿进程与僵尸进程[总结](转载)
- 字符串-不同的编码格式下所占用的字节数【转】
- 企业级应用WebLogic11g集群配置与项目实施_WebLogic部署培训教程
- HDFS数据完整性
- POSIX 线程(一)
- 大端小端的证明
- 第14周-输入输出流,文本文件-项目1 - 小玩文件(2)
- 字典的相关操作
- leetcode - Count Complete Tree Nodes
- C#高级编程第一天