解法一:广度优先遍历

层序遍历。

  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. public int maxDepth(TreeNode root) {
  12. Queue<TreeNode> queue = new LinkedList<>();
  13. if (root != null) {
  14. queue.offer(root);
  15. }
  16. int depth = 0;
  17. while (!queue.isEmpty()) {
  18. ++depth;
  19. int size = queue.size();
  20. for (int i = 0; i < size; ++i) {
  21. TreeNode temp = queue.poll();
  22. if (temp.left != null) {
  23. queue.offer(temp.left);
  24. }
  25. if (temp.right != null) {
  26. queue.offer(temp.right);
  27. }
  28. }
  29. }
  30. return depth;
  31. }
  32. }

解法二:深度优先遍历

每棵树的深度相当于左右子树深度较大值+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. public int maxDepth(TreeNode root) {
  12. return dfs(root);
  13. }
  14. private int dfs(TreeNode root) {
  15. if (root == null) {
  16. return 0;
  17. }
  18. return Math.max(dfs(root.left) + 1, dfs(root.right) + 1);
  19. }
  20. }