本文共 827 字,大约阅读时间需要 2 分钟。
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.
解题思路:
递归求解,如果有比min还小的深度,就更新min,需要注意的是,最小深度是叶子节点到根节点的深度。如果左子树或右子树为空,那么这个就不能计算在内。
public class Solution { int min; public int minDepth(TreeNode root) { min = Integer.MAX_VALUE; DepthOfTree(root,0); return min; } public void DepthOfTree(TreeNode root,int depth){ if(root == null){ if(min > depth) min = depth; return ; } if(root.left == null) DepthOfTree(root.right,depth+1); else if(root.right == null) DepthOfTree(root.left,depth+1); else{ DepthOfTree(root.left,depth+1); DepthOfTree(root.right,depth+1); } }}
转载地址:http://gtivi.baihongyu.com/