二叉树的最大深度
题目描述
求二叉树的最大深度,最大深度指的是,根结点到最远叶子结点经历的结点个数。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int maxDepth (TreeNode root) {
// write code here
if(root == null) return 0; //如果当前结点为空,则高度为0,返回0
int leftDepth = maxDepth(root.left); //计算左子树深度
int rightDepth = maxDepth(root.right); //计算右子树结点深度
return Math.max(leftDepth, rightDepth) + 1; //最大深度为左子树和右子树的最大深度加1
}
}
1470

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



