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.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    

    ##分析 求二叉树的最大深度
    ##解答 ###解法1:(我)递归(1ms) ``` public class Solution { public int maxDepth(TreeNode root) { if (root == null)//根节点为null return 0; else if (root.left == null && root.right == null)//根节点的左右孩子都为null return 1; else if (root.left != null && root.right != null)//根节点的左右孩子都不为null return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; else if(root.left == null)//根节点的左孩子为null,右孩子不为null return maxDepth(root.right) + 1; else//根节点的右孩子为null,左孩子不为null return maxDepth(root.left) + 1; } } ```  
    ###解法2:(我)解法1的优化(1ms) ``` public class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; else return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; } } ```  
    ###解法3:解法2的优化(1ms√) ``` public class Solution { public int maxDepth(TreeNode root) { return (root == null) ? 0 : Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; } } ```
  • 相关阅读:
    CF G. Running Competition (NTT, 思维)
    ABC 177 F
    牛客练习赛68 D.牛牛的粉丝 (期望DP,矩阵快速幂)
    CF E
    HDU 6761 Minimum Index (字符串--Lyndon分解)
    D. GameGame (思维、博弈)
    P2533 最小圆覆盖
    P4049 [JSOI2007]合金
    P2510 [HAOI2008]下落的圆盘
    P3205 [HNOI2010]合唱队
  • 原文地址:https://www.cnblogs.com/xuehaoyue/p/6412672.html
Copyright © 2011-2022 走看看