一、题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路:
求二叉树深度=max(左子树最大深度,右子数最大深度)+1;
使用递归求解左右子树最大深度。

三、代码:
方法一:使用递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
//如果是空二叉树,就返回0
if(root==null){
return 0;
}
//如果只有根结点,就返回1.
if(root.left==null&&root.right==null){
return 1;
}
//递归遍历左右子树
int leftDepth=maxDepth(root.left);
int rightDepth=maxDepth(root.right);
int max=Math.max(leftDepth,rightDepth)+1;
return max;
}
}
方法二:使用层序遍历
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
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;
}

本文详细解析了求解二叉树最大深度的两种方法:递归法和层序遍历法。通过实例展示了算法的具体实现过程,帮助读者深入理解二叉树的遍历与深度计算。

213

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



