题目描述

求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。
代码一:
通过递归

  1. public int maxDepth (TreeNode root) {
  2. // write code here
  3. if(root==null)
  4. return 0;
  5. return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);
  6. }

代码二:
通过层次遍历

  1. //二叉树的深度
  2. public static int maxDepth (TreeNode root) {
  3. if(root==null)
  4. return 0;
  5. // return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);
  6. Queue<TreeNode> q = new LinkedList<TreeNode>();
  7. q.add(root);
  8. int res = 0;
  9. while(!q.isEmpty()) {
  10. int size = q.size();
  11. for(int i=0;i<size;i++) {
  12. TreeNode node = q.poll();
  13. if(node.left!=null)
  14. q.add(node.left);
  15. if(node.right!=null)
  16. q.add(node.right);
  17. }
  18. res++;
  19. }
  20. return res;
  21. }