1. Recursive versions
class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; int left = maxDepth(root.left); int right = maxDepth(root.right); return Math.max(left, right) + 1; }}Copy the code
2. Non-recursive versions
import java.util.LinkedList; import java.util.Queue; class Solution { Queue<TreeNode> queue = new LinkedList<>(); public int maxDepth(TreeNode root) { if (root == null) return 0; queue.offer(root); int depth = 0; while (! queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (node.left ! = null) queue.offer(node.left); if (node.right ! = null) queue.offer(node.right); } depth++; } return depth; }}Copy the code