1. 程式人生 > >104. Maximum Depth of Binary Tree C++ 答案

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

block 方法 int mat rst recursion off HERE space

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)).

參考

  • Official Analysis

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