求给定二叉树的最大深度,
最大深度是指树的根结点到叶子结点
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) {
if(root==null) return 0;
int leftmax=maxDepth(root.left);
int rightmax=maxDepth(root.right);
int max=leftmax>rightmax?leftmax+1:rightmax+1;
return max;
}
}
本文介绍了一种计算二叉树最大深度的方法,通过递归遍历树的左右子节点,找到从根节点到叶子节点的最长路径长度。
1070

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



