zoukankan      html  css  js  c++  java
  • 104. Maximum Depth of Binary Tree

    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.

    Note: A leaf is a node with no children.

    Example:

    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its depth = 3.

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public int maxDepth(TreeNode root) {
    12         if (root == null) return 0;
    13         int d = 0;
    14         if (root.left != null) {
    15             d = Math.max(d, maxDepth(root.left));
    16         }
    17         if (root.right != null) {
    18             d = Math.max(d, maxDepth(root.right));
    19         }
    20         return d + 1;
    21     }
    22 }
  • 相关阅读:
    模板
    2019牛客暑期多校训练营(第五场)
    Codeforces
    Codeforces
    SCUT
    模板
    Codeforces
    2019 Multi-University Training Contest 4
    Codeforces
    Codeforces
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12324176.html
Copyright © 2011-2022 走看看