Simple C++ solution


  • 0
    W

    The ideia is to check if the max depth is in the left subtree or in the right subtree. We can do this using recursion. If we hit a NULL node, he will add nothing to the depth and will be our stop criteria. Otherwise the max depth will be the max value between the right and the left node, the two plus one because we add the actual node to the depth.

    class Solution {
    public:
        
        int maxDepth(TreeNode* root) {
            
            if(root==NULL)
                return 0;
            else{
                return max(maxDepth(root->left)+1,
                           maxDepth(root->right)+1);
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.