• 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));
        }
    };
  • 相关阅读:
    装饰器模式
    java构建树形节点优化
    excel操作
    回调函数
    网络编程
    小练习-接口发布文章 验证未登录
    requests模块
    try异常处理
    内置函数
    接口-用户登录,返回session
  • 原文地址:https://www.cnblogs.com/Makerr/p/14681121.html
Copyright © 2020-2023  润新知