1、深度优先DFS
遍历整颗数,找到每一个叶子节点,从叶子节点往上开始计算,左右子节点都为空则记录深度为1
左右子节点只有一边,深度记录为子节点深度+1 左右两边都有子节点,则记录左右子节点的深度较小值+1
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class leetcode17 {
public static void main(String[] args) {
TreeNode node7=new TreeNode(7,null,null);
TreeNode node6=new TreeNode(6,node7,null);
TreeNode node5=new TreeNode(5,null,null);
TreeNode node4=new TreeNode(4,null,null);
TreeNode node3=new TreeNode(3,node6,null);
TreeNode node2=new TreeNode(2,node4,node5);
TreeNode node1=new TreeNode(1,node2,node3);
System.out.println(dfsminDepth(node1));
}
private static int dfsminDepth(TreeNode root) {
if (root == null){
return 0;
}
if (root.left==null && root.right==null){
return 1;
}
int min=Integer.MAX_VALUE;
if (root.left !=null){
min=Math.min(dfsminDepth(root.left),min);
}
if (root.right !=null){
min=Math.min(dfsminDepth(root.right),min);
}
return min+1;
}
}
|