首页 > 编程语言 > 详细

104. Maximum Depth of Binary Tree C++ 答案

时间:2018-10-13 16:39:54      阅读:197      评论:0      收藏:0      [点我收藏+]

104. Maximum Depth of Binary Tree -- Easy

方法

使用递归

/**
 * 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 calDepthRecursion(TreeNode * node) {
        if(node == NULL) return 0;
        int leftDepth = calDepthRecursion(node->left) + 1;
        int rightDepth = calDepthRecursion(node->right) + 1;
        
        return std::max(leftDepth, rightDepth);
    }
    
    int maxDepth(TreeNode* root) {
        return calDepthRecursion(root);
    }
};
  • Time complexity : we visit each node exactly once, thus the time complexity is \mathcal{O}(N)O(N), where NN is the number of nodes.
  • Space complexity : in the worst case, the tree is completely unbalanced, e.g. each node has only left child node, the recursion call would occur NN times (the height of the tree), therefore the storage to keep the call stack would be \mathcal{O}(N)O(N). But in the best case (the tree is completely balanced), the height of the tree would be \log(N)log(N). Therefore, the space complexity in this case would be \mathcal{O}(\log(N))O(log(N)).

参考

104. Maximum Depth of Binary Tree C++ 答案

原文:https://www.cnblogs.com/optcheng/p/9783253.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!