您的位置:首页 > 其它

LeetCode 二叉树的最小深度

2014-10-20 19:13 357 查看
计算二叉树的最小深度。最小深度定义为从root到叶子节点的最小路径。

Java版本如下:

/**
* Definition for binary tree
* 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)return minDepth(root.right) + 1;
if(root.right == null) return minDepth(root.left) + 1;

return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: