104. 二叉树的最大深度

image.png

递归解法

  1. public class Solution {
  2. public int maxDepth(TreeNode root) {
  3. return recursion(root, 0);
  4. }
  5. // 递归计算树的最大深度
  6. public int recursion(TreeNode node, int depth) {
  7. // 递归终止条件:节点为空,说明到底了
  8. if (node != null) {
  9. // 分别遍历左子树与右子树
  10. return Math.max(recursion(node.left, depth + 1), recursion(node.right, depth + 1));
  11. }
  12. return depth;
  13. }
  14. }

迭代解法

  1. public class Solution {
  2. // 广度优先遍历,该方法类似树的层序遍历,记录树有多少层然后直接返回就行
  3. public int maxDepth(TreeNode root) {
  4. // 记录树深度
  5. int depth = 0;
  6. // 广度优先使用队列存放节点
  7. Queue<TreeNode> queue = new LinkedList<>();
  8. if (root != null) queue.add(root);
  9. while (!queue.isEmpty()) {
  10. // 层数 +1
  11. depth ++;
  12. // 遍历当前层,将下一层的所有节点放入队列
  13. for (int i = queue.size(); i > 0; i --) {
  14. TreeNode tempNode = queue.poll();
  15. if (tempNode.left != null) queue.add(tempNode.left);
  16. if (tempNode.right != null) queue.add(tempNode.right);
  17. }
  18. }
  19. return depth;
  20. }
  21. }