题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:LeetCode
题目分析
(1)涉及树的题,大多可以用递归解,此题也一样,由于是求树的最大深度,则可递归求左右子树的最大深度,然后加1即可得到树的最大深度;
(2)递归的出口条件,是到达了叶子结点。
(3)另外一种解法是层序遍历,但在层序遍历基础上,记录遍历的层数,也可得到树的深度。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){ //递归出口
return 0;
}
else return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
//层序遍历解法
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int res=0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root); //根结点入队
while(!q.isEmpty()){
int size = q.size(); //记录每一层节点数
while(size>0){ //每一层出队完,则深度加1
TreeNode out = q.poll();
if(out.left!=null){
q.offer(out.left);
}
if(out.right!=null){
q.offer(out.right);
}
size--;
}
res++; //记录层数
}
return res;
}
}