Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Solution:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null&&root.right==null) return 1;
return Math.max(1+maxDepth(root.left), 1+maxDepth(root.right));
}
}
本文介绍了一种求解二叉树最大深度的有效算法。通过递归方式,该算法能够找到从根节点到最远叶节点的最长路径,并返回该路径上的节点数。适用于计算机科学与数据结构学习。

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



