目录
二叉树的最大深度
描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明:叶子节点是指没有子节点的节点。
示例
给定二叉树 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回它的最大深度 3
方法:递归
其实本题说到底和前面的题类似,都是对二叉树进行遍历,分左右子树进行访问,访问到了则层数加一。
class Solution {
public int maxDepth(TreeNode root) {
return reCur(root,0);
}
public int reCur(TreeNode root, int depth){
if (root==null) return depth;//如果当前节点为空,直接返回
else{//如果当前节点不为空,层数+1
depth++;
int leftDepth=depth,rightDepth=depth;
if (root.left!=null) leftDepth=reCur(root.left,depth);
if (root.right!=null) rightDepth=reCur(root.right,depth);
return leftDepth>rightDepth?leftDepth:rightDepth;//返回左右子树中深度较大的那个
}
}
}