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;
}
本文介绍了如何通过递归和队列两种方式来计算二叉树的最大深度。最大深度定义为从根节点到最远叶子节点的最长路径上的节点数。递归方法直接利用了二叉树的结构特性,而队列方式则采用层次遍历的思想,逐步深入到树的每一层。两者各有优劣,适用于不同的场景。
412

被折叠的 条评论
为什么被折叠?



