Given a binary tree, find its minimum depth.
The minimum depth isthenumberof nodes along the shortest path fromthe root node down tothe nearest leaf node.
思路:
题意是求一颗二叉树的的最短路径
思路能够參考求二叉树的深度的算法,还是用递归的思想,考虑上级节点和下级左右子树的关系
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/publicclassSolution {publicintminDepth(TreeNode root) {
if(root == null){
return0;
}
if(root.left != null && root.right == null){
return1+minDepth(root.left);
}elseif(root.left == null && root.right != null){
return1+minDepth(root.right);
}else{
return1+Math.min(minDepth(root.left),minDepth(root.right));
}
}
}