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

    Given the root of a binary tree, return its maximum depth.

    A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    Example 1:

    Input: root = [3,9,20,null,null,15,7]
    Output: 3
    

    Example 2:

    Input: root = [1,null,2]
    Output: 2
    

    Example 3:

    Input: root = []
    Output: 0

    Constraints:

    • The number of nodes in the tree is in the range [0, 104].
    • -100 <= Node.val <= 100

    直接递归

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if(!root) return 0;
            else if(!root->left&&!root->right) return 1;
            else return 1+max(maxDepth(root->right),maxDepth(root->left));
        }
    };
    Runtime: 8 ms, faster than 64.32% of C++ online submissions for Maximum Depth of Binary Tree.
    Memory Usage: 18.8 MB, less than 86.84% of C++ online submissions for Maximum Depth of Binary Tree.

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if(!root) return 0;
            else if(!root->left&&!root->right) return 1; //这一步多余
            else return 1+max(maxDepth(root->right),maxDepth(root->left));
        }
    };
    Runtime: 4 ms, faster than 92.07% of C++ online submissions for Maximum Depth of Binary Tree.
    Memory Usage: 18.8 MB, less than 49.92% of C++ online submissions for Maximum Depth of Binary Tree.
    也可改写成三元运算符的形式
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            return root==NULL?0:1+max(maxDepth(root->left),maxDepth(root->right));
        }
    };
  • 相关阅读:
    codevs 2021 中庸之道
    bzoj 1227: [SDOI2009]虔诚的墓主人
    cogs 2620. [HEOI2012]朋友圈
    bzoj 3123: [Sdoi2013]森林(45分暴力)
    cogs 1685 魔法森林
    bzoj 1061: [Noi2008]志愿者招募
    poj 1743 Musical Theme
    bzoj 1001: [BeiJing2006]狼抓兔子
    bzoj 4006: [JLOI2015]管道连接
    hdu 5693 D Game
  • 原文地址:https://www.cnblogs.com/Makerr/p/14681121.html
Copyright © 2011-2022 走看看