①递归求最大深度
class Solution {
public int maxDepth(TreeNode root) { //二叉树的最大深度
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
②层序遍历求最大深度
class Solution {
public int maxDepth(TreeNode root) { 层序遍历模板
if (root == null) return 0;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
int depth = 0;
while (!que.isEmpty())
{
int len = que.size();
while (len > 0)
{
TreeNode node = que.poll();
if (node.left != null) que.offer(node.left);
if (node.right != null) que.offer(node.right);
len--;
}
depth++;
}
return depth;
}
}
①递归求二叉树的最小深度
重点在递归终止条件。
class Solution {
public int minDepth(TreeNode root) { //深度遍历 + 递归
if (root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
return left == 0 || right == 0 ? 1 + left + right : 1 + Math.min(left, right);
}
}
②层序遍历求最小深度
创建QueueNode(TreeNode node, int depth),利用队列,遇到左右孩子都为null的时候即可返回depth。
class Solution {
class QueueNode {
TreeNode node;
int depth;
public QueueNode(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<QueueNode> queue = new LinkedList<QueueNode>();
queue.offer(new QueueNode(root, 1));
while (!queue.isEmpty()) {
QueueNode nodeDepth = queue.poll();
TreeNode node = nodeDepth.node;
int depth = nodeDepth.depth;
if (node.left == null && node.right == null) return depth;
if (node.left != null) queue.offer(new QueueNode(node.left, depth + 1));
if (node.right != null) queue.offer(new QueueNode(node.right, depth + 1));
}
return 0;
}
}