题目
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.
分析
求二叉树的最小深度:根节点到最近叶子节点的路径长度。
同样采用递归的思想:
- 当根节点为空,返回0;
- 当根节点为唯一的二叉树节点时,返回1;
- 否则,求解并返回 最小(非空,保证最终到达叶节点)左右子树深度 + 1;
class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; if(root.left==null&&root.right==null) return 1; else { int leftdepth; int rightdepth; if(root.left!=null) { leftdepth=minDepth(root.left); } else leftdepth=Integer.MAX_VALUE; if(root.right!=null) { rightdepth=minDepth(root.right); } else rightdepth=Integer.MAX_VALUE; return 1+Math.min(leftdepth, rightdepth); } }