一、题目内容

image.png

二、题解

解法1:

思路

深度优先;求左子树与右子树最大深度,然后+1

代码

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * 递归
  13. *
  14. * @param root
  15. * @return
  16. */
  17. public int maxDepth(TreeNode root) {
  18. if (root == null) {
  19. return 0;
  20. }
  21. return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
  22. }
  23. }

解法2:

思路

广度优先;层序遍历,每遍历一层,则计数器 +1+1

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    /**
     * 广度优先,层序遍历
     *
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode head = queue.poll();
                if (head.left != null) {
                    queue.offer(head.left);
                }
                if (head.right != null) {
                    queue.offer(head.right);
                }
            }
            depth++;
        }
        return depth;
    }
}