Question
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Code
递归方式
/**
* 递归的方式
*
* @param root
* @return
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
队列的方式
/**
* 队列的方式
*
* @param root
* @return
*/
public int maxDepth1(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queues = new LinkedList<>();
queues.add(root);
int level = 0;
while (!queues.isEmpty()) {
int len = queues.size();
level++;
for (int i = 0; i < len; i++) {
TreeNode t = queues.poll();
if (t.left != null) {
queues.offer(t.left);
}
if (t.right != null) {
queues.offer(t.right);
}
}
}
return level;
}