97. Maximum Depth of Binary Tree

痛定思痛。 2022-05-27 04:53 294阅读 0赞

97. Maximum Depth of Binary Tree

Description

  1. Given a binary tree, find its maximum depth.
  2. The maximum depth is the number of nodes along the longest path
  3. from the root node down to the farthest leaf node.

Example

  1. Given a binary tree as follow:
  2. 1
  3. / \
  4. 2 3
  5. / \ 4 5

Solution

  1. /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */
  2. public class Solution {
  3. /** * @param root: The root of binary tree. * @return: An integer */
  4. public int maxDepth(TreeNode root) {
  5. if(root!=null){
  6. int dl = maxDepth(root.left);
  7. int dr = maxDepth(root.right);
  8. int maxD = dl>dr?dl:dr;
  9. return maxD+1;
  10. }else{
  11. return 0;
  12. }
  13. }
  14. }

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读