码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-13 16:50:35      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:c++   bin   binary   --   mes   public   null   ble   block   

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++ 答案

标签:c++   bin   binary   --   mes   public   null   ble   block   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!