Sharing my simple C++ solution(8 ms)


  • 1
    A
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
    		if(root == NULL)
    			return 0;
    		int lDepth = maxDepth(root->left) + 1;
    		int rDepth = maxDepth(root->right) + 1;
    		return (lDepth > rDepth)? lDepth : rDepth;
        }
    };

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

  • 0
    Y

    This solution is 12 ms, here is the 8 ms version

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

    reducing 1 stack frame by checking the left and right before calling the method


Log in to reply
 

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