/**
* 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) {
//题目要找的是从根结点到叶结点的最短距离,所以一定要找到叶结点
//若没有从根结点到叶结点的就返回1,毕竟求的是树的深度
//若从根结点到叶结点只有一条路径,则这条路径就是最短的
//若从根结点到叶结点有两条路径,则找出两条路径的长度的最小值
int res = 0;
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
if(root.left != null && root.right != null)
return Math.min(1 + minDepth(root.left), 1 + minDepth(root.right));
if(root.left == null) return 1 + minDepth(root.right);
if(root.right == null) return 1 + minDepth(root.left);
return res;
}
}
leetcode [Minimum Depth of Binary Tree]//待整理多种解法
最新推荐文章于 2019-10-10 21:42:22 发布