美文网首页
LeetCode - 0104 - Maximum Depth

LeetCode - 0104 - Maximum Depth

作者: 大圣软件 | 来源:发表于2017-07-30 22:35 被阅读0次

    题目概述

    求一个二叉树的树深。

    原题链接

    Maximum Depth of Binary Tree

    解题思路

    递归的思路,一个二叉树的树深就是它子树的最大树深加一。

    复杂度分析

    时间复杂度:$O(n)$,$n$为树中的字典数目。并且该复杂度是串行搜索节点时的情形。

    代码

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if(root == NULL) return 0;
            int l = maxDepth(root->left), r = maxDepth(root->right);
            return l>r? l+1:r+1;
        }
    };
    

    广告区域

    本人和小伙伴们承接各种软件项目,有需求的可以联系我们。
    QQ: 2992073083

    相关文章

      网友评论

          本文标题:LeetCode - 0104 - Maximum Depth

          本文链接:https://www.haomeiwen.com/subject/mqaklxtx.html