import java.util.LinkedList;
public class MaxDepth {
public static void main(String[] args) {
}
//思路1
//递归求解树的最大深度
//树的深度等于左子树的深度和右子树的深度中的最大值 + 1
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;//空树的深度为0
}
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;//树的深度等于左子树的深度和右子树的深度中的最大值 + 1
}
//思路2:广度优先遍历
//广度优先搜索的队列里存放的是「当前层的所有节点」。
// 每次拓展下一层的时候,不同于广度优先搜索的每次只从队列里拿出一个节点,我们需要将队列里的所有节点都拿出来进行拓展,
// 这样能保证每次拓展完的时候队列里存放的是当前层的所有节点,即我们是一层一层地进行拓展,
// 最后我们用一个变量 ans来维护拓展的次数,该二叉树的最大深度即为 ans
public int maxDepthByBFS(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);//加入根节点
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size(); //需要将队列里的所有节点都拿出来进行拓展
while (size > 0) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);//加入下一层的结点
}
if (node.right != null) {
queue.offer(node.right);加入下一层的结点
}
size --;
}
//没遍历完一层,树的深度 + 1
depth ++;
}
return depth;
}
}
//树的结点类
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
求二叉树的最大深度的两种思路及JAVA代码实现
最新推荐文章于 2023-12-06 12:13:40 发布