树的最大深度-java实现

使用递归的方法最为简洁、高效;通过主次遍历,主要不为空,书的深度就加一,同时比较右侧树的深度,每次返回最大值;

 

1  public int maxDepth(TreeNode root) {
2         return root==null?0:Math.max(maxDepth(root.left)+1,maxDepth(root.right)+1);
3     }
View Code

 

posted @ 2023-05-28 21:27  Mexcellent  阅读(24)  评论(0)    收藏  举报